"Python" Python's Time and datetime modules

Source: Internet
Author: User
Tags timedelta

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

# 默认四舍五入到整数位,即不保留小数print(round(time.time()))# 可指定参数保留的小数位数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秒后才打印这句print(‘yes‘)
goodyes

The use of some other functions

# 返回UTC时间print(time.gmtime())# 返回本地时间,在中国就是UTC+8print(time.localtime())
 time.struct_time (Tm_year= 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())# 由于使用默认参数和上面的结果一样print(time.ctime(time.time()))print(time.asctime(time.localtime()))
 thu Jul 6 09:46:15 2017Thu Span class= "Hljs-selector-tag" >jul 6 09:46 : 2017thu jul 6 09 :46:15 2017 thu jul 6 09 : 46:15          
    • 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< Span class= "St" > "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

= 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

= time.clock()print(start)  # 2.6773594453225194e-06time.sleep(2)end = time.clock()print(end - start) # 差值代表了睡眠2秒的时间。2.000246763295544time.sleep(3)print(time.clock()) # 5.00058991153112,返回的是从第一次调用到这次调用的时间间隔
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.

from DateTime import datetime # return current time now = datetime.now () print (now.year, Now.month, Now.microsecond) # can customize parameters, return formatted time after DT = datetime (2017, 10, 1, 23, 59, 59,  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.

# 时间戳转datetimenow = datetime.fromtimestamp(time.time())print(now)sometime = datetime(2017, 7, 5, 23, 59, 59)# datetime转时间戳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

= datetime(2017, 5, 31)dt2 = datetime(2017, 4, 1)print(dt1 - dt2)print(dt1 > dt2)
days, 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 ()) # is only in seconds to denote this 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

"Python" Python's Time and datetime modules

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.