Python time: second-to-String Conversion

Source: Internet
Author: User
Tags glob julian day month name timedelta

1) number of seconds = "string

1234567 from
time
import
*
 def
secs2str(secs):
        return
strftime("%Y-%m-%d %H:%M:%S",localtime(secs)) >>> secs2str(1227628280.0)'2008-11-25 23:51:20'

2) string = "seconds

123456 from
time
import
*
# First parse the time string into 9 tuples, for example:#23:51:20, parsed as 9 tuples: [, 0].>>> tmlist
= [2008,11,25,23,51,20,0,0,0]>>> mktime(tmlist)1227628280.0

Complete functions:

12345678910 def
secs2str(secs):
    "Converts seconds to strings """    if
int(secs) <
0:        return
""    return
str(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(secs)))def
str2secs(tmlist
=[]):    "Converts string time to seconds """    if
len(tmlist) !=
9:        return
0    return
int(time.mktime(tmlist))

Partial Translation of the time module of Python:
I. Introduction

The time module provides functions for various operation times.
Note: There are two methods to indicate time:
The first method is the timestamp (offset calculated in seconds relative to 00:00:00). The timestamp is unique.
The second type is represented as an array (struct_time). There are nine elements, respectively, indicating that the struct_time of the same timestamp varies with the time zone.

Year (four digits, e.g. 1998)
Month (1-12)
Day (1-31)
Hours (0-23)
Minutes (0-59)
Seconds (0-59)
Weekday (0-6, Monday is 0)
Julian day (day in the year, 1-366)
Whether DST (daylight savings time) flag (-1, 0 or 1) Is Daylight Saving Time
If the DST flag is 0, the time is given in the regular time zone;
If it is 1, the time is given in the DST time zone;
If it is-1, mktime () shoshould guess based on the date and time.

Ii. Function Introduction
1. asctime ()
Asctime ([tuple])-> string
Converts a struct_time (default time) to a string.
Convert a time tuple to a string, e.g. 'sat Jun 06 16:26:11 123 ′.
When the time tuple is not present, current time as returned by localtime ()
Is used.

2. Clock ()
Clock ()-> floating point number
This function has two functions,
During the first call, the actual running time is returned;
After the second call, the returned time interval from the first call to the current call is

Example:

view plaincopy to clipboardprint?import timeif __name__ == '__main__':    time.sleep(1)    print "clock1:%s" % time.clock()    time.sleep(1)    print "clock2:%s" % time.clock()    time.sleep(1)    print "clock3:%s" % time.clock()

Output:
Clock1: 3.35238137808e-006
Clock2: 1.00004944763
Clock3: 2.00012040636
The first clock outputs the program running time.
The second and third clock outputs are the time interval from the first clock.

3. Sleep (...)
Sleep (seconds)
The thread delays running at a specified time. After testing, the unit is seconds. However, there is one of the following statements in the help document, which cannot be understood.
"The argument may be a floating point number for subsecond precision ."

4. ctime (...)
Ctime (seconds)-> string
Converts a timestamp (current time by default) into a time string.
For example:

  time.ctime()

Output: 'sat Mar 28 22:24:24 123 ′

5. gmtime (...)
Gmtime ([seconds])-> (tm_year, tm_mon, tm_day, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst)
Converts a timestamp to struct_time of UTC time zone (0 Time Zone). If the seconds parameter is not input, the current time is used as the conversion standard.

6. localtime (...)
Localtime ([seconds])-> (tm_year, tm_mon, tm_day, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst)
Converts a timestamp to struct_time of the current time zone. If the seconds parameter is not input, the current time is used as the conversion standard.

7. mktime (...)
Mktime (tuple)-> floating point number
Converts a struct_time to a timestamp.

8. strftime (...)
Strftime (Format [, tuple])-> string
Returns the specified struct_time (current time by default) according to the specified formatted string.
Time and date formatting symbols in Python:
% Y two-digit year (00-99)
% Y indicates the four-digit year (000-9999)
% M month (01-12)
One day in % d month (0-31)
% H hour in 24-hour format (0-23)
% I 12-hour (01-12)
% M minutes (00 = 59)
% S seconds (00-59)

% A local simplified week name
% A local full week name
% B local simplified month name
% B local full month name
% C local Date and Time
% J one day in the year (001-366)
% P local equivalent of a. m. or P. M.
% U number of weeks in a year (00-53) Sunday is the start of the week
% W Week (0-6), Sunday is the beginning of the week
% W number of weeks in a year (00-53) Monday is the start of the week
% X local date Representation
% X Local Time Representation
% Z Current Time Zone name
% Itself

9. strptime (...)
Strptime (string, format)-> struct_time
Converts a time string to a time string in the array format based on the specified formatting character.
For example:
The format string for 11:45:39 is: % Y-% m-% d % H: % m: % s
Sat Mar 28 22:24:24 2009 formatted string: % A % B % d % H: % m: % S % Y

10. Time (...)
Time ()-> floating point number
Returns the timestamp of the current time.

Iii. Doubts
1. Renewal
In struct_time, it seems useless to parse, for example
A = (2009, 6, 28, 23, 8, 34, 5, 87, 1)
B = (2009, 6, 28, 23, 8, 34, 5, 87, 0)
A and B indicate the time stamp and the standard time respectively. The conversion between them is related to the timestamp 3600, but the output is 646585714.0 after the conversion.

4. Small applications
1. Obtain the current time using Python
Time. Time () Get the current Timestamp
Time. localtime () struct_time form of the current time
Time. ctime () string format of the current time

2. format strings in Python
Formatted as 11:45:39

  time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

Formatted as sat Mar 28 22:24:24 2009

  time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())

3. Convert the format string to the timestamp

A = "sat Mar 28 22:24:24 2009" B = time. mktime (time. strptime (a, "% A % B % d % H: % m: % S % Y") details of the python time datetime ModuleTime module:-------------------------- Time () # returns the number of seconds since the Linux New Century in floating point format. In Linux, 00:00:00 UTC, January 1, 1970 is the start of the new ** 49 **. >>> Time. time () 1150269086.6630149 >>> time. ctime (1150269086.6630149) >>> 'wed Jun 14 15:11:26 100' time. ctime ([SEC]) # converts the number of seconds to the date format. If no parameter is specified, the current time is displayed. >>> Import time >>> time. ctime () >>> 'wed Jun 14 15:02:50 100' >>> time. ctime (1138068452427683) 'sat dec 14 04:51:44 1111'> time. ctime (OS. path. getmtime ('e: \ untitleds.bmp ') 'fri Sep 19 16:35:37 2008' >>> time. gmtime (OS. path. getmtime ('e: \ untitleds.bmp ') time. struct_time (tm_year = 2008, tm_mon = 9, tm_mday = 19, tm_hour = 8, tm_min = 35, tm_sec = 37, tm_wday = 4, tm_yday = 263, tm_isdst = 0) convert the modification time of a file to the date format (second to date) >>> tim E. strftime ('% Y-% m-% d % x', time. localtime (OS. path. getmtime ('e: \ untitleds.bmp ') '2017-09-19 16:35:37' # scheduled for 3 seconds. >>> Time. Sleep (3)Time module reference:--------------------------------- # Obtain the modification time of an object >>> OS. path. getmtime ('e: \ untitleds.bmp ') 1221813337.7626641 difference between the timezone universal coordination time and the local standard time, in seconds. The daylight mark of the difference between the altzone universal coordination time and the local Daylight Saving Time. Whether the local time reflects the daylight saving time. Tzname (Standard Time Zone name, Time Zone name in milliseconds) function time () returns the number of seconds since the epoch. Clock () returns the time when the CPU starts the process with a floating point number (or the time when this function is called the first time) sleep () delays a period of seconds represented by a floating point number. Gmtime () converts the time expressed in seconds to the universal coordination time sequence localtime () converts the second to the local time sequence asctime () converts the time sequence to the text description ctime () converts a second to a text description mktime () and converts a local time series to a second. strftime () converts a sequence to a text description strptime () in a specified format () parses the time series tzset () from the text description in the specified format to change the local time zone value.Datetime Module---------------------------- Datetime converts a date to seconds ----------------------------------------- >>> import datetime, time >>> time. mktime (datetime. datetime (2009,1, 1 ). timetuple () 1230739200.0 >>> cc = [, 11,] # attributes: year, month, day, hour, minute, second >>> time. mktime (datetime. datetime (CC [0], CC [1], CC [2], CC [3], CC [4], CC [5]). timetuple () 973226613.0 converts seconds to the date format >>> cc = time. localtime (OS. path. getmtime ('e: \ untitleds.bmp ') >>> print CC [0: 3] (2008, 9, 19)Datetime example----------------- Demo calculation of two days of date difference >>> import datetime >>> d1 = datetime. datetime (2005, 2, 16) >>> D2 = datetime. datetime (2004, 12, 31) >>> (D1-D2 ). days47 demonstrates the example of calculating the running time. Import datetimestarttime = datetime is displayed in seconds. datetime. now () # Long runningendtime = datetime. datetime. now () print (endtime-starttime ). seconds demonstrates how to calculate the time from the current time to the next 10 hours. >>> D1 = datetime. datetime. now () >>> D3 = D1 + datetime. timedelta (hours = 10) >>> d3.ctime () The common classes in this document are datetime and timedelta. They can be added or subtracted from each other. Each class has some methods and attributes to view specific values.3) globYou can use a simple method to match all subdirectories or files in a directory. 3.1 glob. glob (regression) returns a list 3.2 glob. iglob (regression) returns a traversal tool. This module is easy to use and highly recommended.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.