Python's time and datetime modules are detailed

Source: Internet
Author: User
Tags element groups timedelta
There are three types of time-performance formats in the Times module:

A, timestamp timestamp, which represents the offset calculated in seconds from January 1, 1970 00:00:00

B, struct_time time tuple, a total of nine element groups.

C, format time formatting times, formatted structure makes time more readable. Includes custom formats and fixed formats.

Time

Common have time.time() and time.sleep() functions.

Import Timeprint (Time.time ())
1499305554.3239055

The floating-point number above is called the Unix epoch timestamp, which is the seconds from 0 O'Clock January 1, 1970 to today. you can see that there are 6 decimal places in the back, and round you can use functions to round up floating-point numbers. As follows

# Default rounding to integer digits, i.e. no fractional print (round (Time.time ())) # can specify the number of decimal places to retain the parameter print (round (Time.time (), 2))
14993055541499305554.49

time.sleep(sec)Can let the current hibernate, the parameter fills in seconds (s).

Print (' good ') Time.sleep (5.5) # 5.5 seconds before printing this line (' Yes ')
Goodyes

The use of some other functions

# return UTC time Print (Time.gmtime ()) # Return local time, in China is Utc+8print (Time.localtime ())
Time.struct_time (tm_year=2017, tm_mon=7, tm_mday=6, Tm_hour=1, tm_min=46, tm_sec=0, tm_wday=3, tm_yday=187, tm_isdst=0 ) Time.struct_time (tm_year=2017, tm_mon=7, tm_mday=6, tm_hour=9, tm_min=46, tm_sec=0, tm_wday=3, tm_yday=187, tm_isdst= 0)

It can be found that this is a tuple type, Chinese location utc+8, can be found in addition to the tm_hour same (they differ by just +8), the rest are the same.

The following function can return a formatted datetime and look more intuitive.

Print (Time.ctime ()) print (Time.asctime ()) # because the default parameters are the same as the above results, print (Time.ctime (Time.time ())) Print (Time.asctime ( Time.localtime ()))
Thu Jul  6 09:46:15 2017Thu Jul  6 09:46:15 2017Thu Jul  6 09:46:15 2017Thu Jul  6 09:46:15 2017
    • ctime()You can pass in a timestamp, and the current timestamp is used as the parameter by default when no parameters are specified. Thattime.time()

    • gtime()You can pass in a struct_time, and the current time is used by default when no parameters are specified. Thattime.localtime()

Struct_time conversion to string and string to Struct_time

    • The first parameter of Strptime is a date in the form of a string, and the second parameter is a custom date conversion format. The format of the two parameters must correspond. For example time.strptime('2017/7/6', '%Y-%m-%d') , a use of a slash, one with a short horizontal line, will be an error. This function returns a Struct_time

    • The first parameter of strftime is the date format that you want to convert to, the second parameter is a struct_time, which converts the struct_time of the tuple form to the format specified by the first parameter, and returns the converted date string form.

%Y-%m-%dThe datetime module is described in detail in the date.

A = Time.strptime (' 2017/7/6 ', '%y/%m/%d ') b = time.strftime ('%y-%m-%d ', Time.localtime ()) print (a) print (b)
Time.struct_time (tm_year=2017, tm_mon=7, tm_mday=6, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=187, Tm_isdst=-1 ) 2017-07-06

Elapsed time of the measuring program

Time stamp makes it easy to time a program to run

Start_time = Time.time () sum = 0for i in range (10000000): Sum + = 1end_time = Time.time () print (end_time-start_time)
2.185124397277832

You can see that the execution loop calculates the addition 10 million times, and that program took more than 2 seconds.

You can also use time.clock() functions

Start = Time.clock () print (start)  # 2.6773594453225194e-06time.sleep (2) end = Time.clock () print (End-start)  # The difference represents the time to sleep for 2 seconds. 2.000246763295544time.sleep (3) print (Time.clock ())  # 5.00058991153112, which returns the interval from the first call to this call
4.4622657422041984e-072.00260060847455675.013243112269714

clockIt is strange to see the first call, which returns the time the process ran . The next call is the difference from the value of the first call clock . That is, the time from the start of the first call to the current call clock .
As above, set start at the top of the code you want to test, set end in place, subtract can also get the fragment code run time, and more time.time() accurate.

Datetime

datetime模块Used to manage dates and times, where there are three of submodules. Yes time、date、datetime , so you can use the following import method if you want to use DateTime.

The From datetime import datetime# returns the current time now = DateTime.Now () print (Now.year, Now.month, Now.microsecond) # You can customize the parameters, Returns the formatted time after dt = datetime (1, max, 456123) print (DT)
2017 7 7196092017-10-01 23:59:59.456123

DateTime accepts 7 parameters, corresponding to year, month, day, time, minute, second, and Microsecond respectively. are stored in the properties of the DateTime, respectively year、month、day、hour、minute、second、microsecond .

The timestamp can be converted into a datetime type. As below, use the timestamp of the current time. is actually equivalent to datetime.now() . Of course, it is also possible to get timestamps by DateTime.

# timestamp to Datetimenow = Datetime.fromtimestamp (Time.time ()) print (now) sometime = DateTime (7, 5,.) # DateTime Turn Time Stamp print (Sometime.timestamp ())
2017-07-06 09:46:07.9037691499270399.0

These datetime objects can use ><= symbols to compare the order of two dates. You can also perform a subtraction operation that represents the difference of two moments. Like what

DT1 = DateTime (5, +) DT2 = DateTime (4, 1) print (DT1-DT2) print (Dt1 > DT2)
0:00:00true

Timedelta represents a period of time

Note that it does not represent a moment, but a period of time.

Import Datetimedelta = Datetime.timedelta (weeks=2, days=7, Hours=1, seconds=59,microseconds=234353) delta1 = Datetime.timedelta (days=5, hours=2) print (delta.seconds)  # Return properties hours and seconds and print (Delta.total_seconds ()) # Just seconds to show the time print (Delta > delta1) print (Delta + delta1)
36591818059.234353true26 days, 3:00:59.234353

The accepted parameters of Timedelta are weeks、days、hours、minutes、seconds、microseconds , but their properties are only days、seconds、microseconds . Besides supporting size comparisons and subtraction operations like datetime, addition operations can be performed to represent the difference of two time periods .

Converts a datetime to a string and a string to a DateTime object

The time module also has these two functions (see the example above), which are similar in use.

    • Strptime converts a date in the form of a string into a DateTime object in the specified format and returns.

    • Strftime converts a DateTime object, such as now, into a string and returns according to the specified format.

from datetime import Datetimea = Datetime.strptime (' 2017/7/6 ', '%y/%m/%d ') b = DateTime.Now (). Strftime ('%y-%m-%d ') print (a) print (b)
2017-07-06 00:00:002017-07-06

For a date-time format, look at the table below.

Format Directives meaning
%Y Four-bit years with a century, such as 2017
%y The post two-bit year, such as 17, means 2017
%m month, from 01 to 12
%B Full month, such as November
%b Abbreviations of the month, such as Nov
%d The day of the one month, as from 01 to 31 (if any)
%j The day ordinal of a year
%w The day of the week
%A A complete week, as Monday
%a Abbreviated weeks, such as Mon
%H 24-Hour Hour 00-23
%h 12-Hour Hour 01-12
%M Points, 00-59
%s Seconds, 00-59
%p AM or PM

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.