The most troublesome time for Python is medicine.

Source: Internet
Author: User
Tags timedelta

Https://www.cnblogs.com/sunshineyang/p/6818834.html

One: The time method used frequently

1. Get the current time

  uses the time module to first get the current timestamp in [Time.time]: +/-(): 1408066927.208922 converts the timestamp to a time tuple Struct_timein [43]: Time.localtime (Time.time ()) out[43]: Time.struct_time (tm_year=2014, tm_mon=8, tm_mday=15, tm_hour=9, tm_min=42, tm_ Sec=20, tm_wday=4, tm_yday=227, tm_isdst=0) format output desired time in []: Time.strftime ('%y-%m-%d%h:%m:%s ', Time.localtime ( Time.time ())) out[44]: ' 2014-08-15 09:43:04 ' next, without parameters, the default is to output the current time in []: Time.strftime ('%y-%m-%d%h:%m:%s ') out[48]: ' 2014-08-15-09:46:53 ' Of course, it can also be implemented through a DateTime module, as follows: in [time.time]: T = + () in []: Datetime.datetime.fromtimestamp (t). Strftime ('%y-%m-%d%h:%m:%s ') out[69]: ' 2014-08-15 10:04:51 ' Also, you can use only the DateTime module in []: Datetime.datetime.now (). Strftime ('%y-%m-%d%h:%m:%s ') out[46]: ' 2014-08-15 09:45:27 ' in []: Datetime.datetime.today (). Strftime ('%y-%m-%d%H: %m:%s ') out[47]: ' 2014-08-15 09:46:10 ' 

2. Get the time difference, calculate the execution times of the program, and so on:
使用time模块:In [75]: def t():   ....:     start = time.time()   ....:     time.sleep(10)   ....:     end = time.time()   ....:     print end - start   ....:In [76]: t()10.0014948845使用datetime模块:In [49]: starttime = datetime.datetime.now()In [50]: endtime = datetime.datetime.now()In [51]: print (endtime - starttime).seconds6


3. Calculate yesterday's date (divergent thinking, calculate other date addition, subtraction, etc.):

In [52]: d1 = datetime.datetime.now()In [53]: d2 = d1 - datetime.timedelta(days=1)In [54]: d1Out[54]: datetime.datetime(2014, 8, 15, 9, 54, 10, 68665)In [55]: d2Out[55]: datetime.datetime(2014, 8, 14, 9, 54, 10, 68665)

4. Time-tuple Struct_time converted to timestamp
In [56]: datetime.datetime.now()Out[56]: datetime.datetime(2014, 8, 15, 9, 57, 52, 779893)In [57]: datetime.datetime.now().timetuple()Out[57]: time.struct_time(tm_year=2014, tm_mon=8, tm_mday=15, tm_hour=9, tm_min=58, tm_sec=12, tm_wday=4, tm_yday=227, tm_isdst=-1)In [58]: time.mktime(datetime.datetime.now().timetuple())Out[58]: 1408067904.0


5.strptime is also useful for converting a time string to a time tuple struct_time
In [73]: time.strftime(‘%Y-%m-%d %H:%M:%S‘)Out[73]: ‘2014-08-15 10:27:36‘In [74]: time.strptime(‘2014-08-15 10:27:36‘,‘%Y-%m-%d %H:%M:%S‘)Out[74]: time.struct_time(tm_year=2014, tm_mon=8, tm_mday=15, tm_hour=10, tm_min=27, tm_sec=36, tm_wday=4, tm_yday=227, tm_isdst=-1)

# #二: Introduction to common methods of time and DateTime modules

Two ways to represent time:

1. 时间戳(相对于1970.1.1 00:00:00以秒计算的偏移量),时间戳是惟一的2. 时间元组 即(struct_time),共有九个元素,分别表示,同一个时间戳的struct_time会因为时区不同而不同

A few common methods of time module

1.time.clock ()

这个需要注意,在不同的系统上含义不同。在UNIX系统上,它返回的是“进程时间”,它是用秒表示的浮点数(时间 戳)。而在WINDOWS中,第一次调用,返回的是进程运行的实际时间。而第二次之后的调用是自第一次调用以后到现在的运行时间。(实际上是以WIN32 上QueryPerformanceCounter()为基础,它比毫秒表示更为精确)[email protected]:/tmp$ cat clock.py#!/usr/bin/env pythonimport 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()运行脚本:[email protected]:/tmp$ ./clock.pyclock1:0.059173clock2:0.059299clock3:0.059416


2.time.sleep (secs)

线程推迟指定的时间运行适合放在脚本里,定时sleep一会然后继续干啥In [138]: while True:   .....:     time.sleep(3)   .....:     print time.strftime(‘%H:%M:%S‘)   .....:17:21:3517:21:3817:21:4117:21:44……

3.time.localtime ([secs])

将一个时间戳转换成一个当前时区的struct_time,如果seconds参数未输入,则以当前时间为转换标准未提供secs参数时,按当前时间为准In [141]: time.localtime()Out[141]: time.struct_time(tm_year=2014, tm_mon=8, tm_mday=14, tm_hour=17, tm_min=23, tm_sec=48, tm_wday=3, tm_yday=226, tm_isdst=0)提供secs为当前时间戳时In [142]: time.time()Out[142]: 1408008232.217969In [143]: time.localtime(time.time())Out[143]: time.struct_time(tm_year=2014, tm_mon=8, tm_mday=14, tm_hour=17, tm_min=24, tm_sec=2, tm_wday=3, tm_yday=226, tm_isdst=0)


4.time.strftime (format[, T])

将指定的struct_time(默认为当前时间),根据指定的格式化字符串输出t未指定,传入time.localtime()作为默认参数:In [156]: time.strftime(‘%Y-%m-%d %H:%M:%S‘)Out[156]: ‘2014-08-14 17:28:16’指定t为time.localtime(1407945600.0)时:In [157]: time.localtime(1407945600.0)Out[157]: time.struct_time(tm_year=2014, tm_mon=8, tm_mday=14, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=226, tm_isdst=0)In [158]: time.strftime(‘%Y-%m-%d %H:%M:%S‘,time.localtime(1407945600.0))Out[158]: ‘2014-08-14 00:00:00’


5.time.time ()

返回当前时间的时间戳In [161]: time.time()Out[161]: 1408008711.730218

6.time.mktime (t)

将一个struct_time转换为时间戳,如下time.localtime接收一个时间戳返回一个struct_time,而time.mktime接收一个struct_time,返回一个时间戳In [159]: time.localtime(1407945600.0)Out[159]: time.struct_time(tm_year=2014, tm_mon=8, tm_mday=14, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=226, tm_isdst=0)In [160]: time.mktime(time.localtime(1407945600.0))Out[160]: 1407945600.0残阳似血的博客:


# Common methods of #datetime module

The most common types of datetime modules are the following four classes:

1. datetime.date: 是指年月日构成的日期(相当于日历)2. datetime.time: 是指时分秒微秒构成的一天24小时中的具体时间(相当于手表)3. datetime.datetime: 上面两个合在一起,既包含时间又包含日期4. datetime.timedelta: 时间间隔对象(timedelta)。一个时间点(datetime)加上一个时间间隔(timedelta)可以得到一个新的时间点(datetime)。比如今天的上午3点加上5个小时得到今天的上午8点。同理,两个时间点相减会得到一个时间间隔。


1.datetime.date class

  1. Create a new Date object that can either call Datetime.date.today () directly or directly to Datetime.date (), as follows: in [4]: Today = Datetime.date.today () in [5]: Todayout[5]: datetime.date (8, +) in [6]: t = datetime.date (2014,8,15) in [7]: Tout[7]: D Atetime.date (8, 2.datetime.date.strftime) format to take time, such as the usual "year-month-day hours: minutes: Seconds" format in [8]: today.strftime ('%y- %m-%d%h:%m:%s ') out[8]: ' 2014-08-15 00:00:00 ' Date object in hours, minutes, seconds default is 0, that that time 3.datetime.date.timple () into struct_time format, After this is passed to Time.mktime (t), it is converted directly into timestamp format in [9]: Today.timetuple () out[9]: Time.struct_time (tm_year=2014, tm_mon=8, tm_mday=15, Tm_hour=0, Tm_min=0, tm_sec=0, tm_wday=4, tm_yday=227, Tm_isdst=-1) in [ten]: Time.mktime (Today.timetuple ()) Out[10]: 1408032000.04.datetime.date.replace (year, month, day) returns a replaced Date object in [all]: Today.replace (year=2013) out[11]: Datetime.date (8, 5.datetime.date.fromtimestamp) converts the timestamp to a Date object in [12]: Datetime.date.fromtimestamp (1408058729) out[12]: datetime.date (8, +)  


2.datetime.time class

1.新建一个time对象In [15]: tOut[15]: datetime.time(8, 45, 20)2.datetime.time.(format)格式化输出In [16]: t.strftime(‘%Y-%m-%d %H:%M:%S‘)Out[16]: ‘1900-01-01 08:45:20’time对应的年、月、日为1900、01、01,纪元年的那个时间3.datetime.time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]]) 返回一个替换后的time对象In [17]: t.replace(hour=9)Out[17]: datetime.time(9, 45, 20)


3.datetime.datetime class

In fact, and the date of those methods, probably look at the following, briefly say 1. Create a new DateTime object with the date today, either directly calling Datetime.datetime.today () or directly to Datetime.datetime () , as follows: in [+]: D1 = Datetime.datetime.today () in [all]: d1out[22]: Datetime.datetime (8, 8, A, A, 790945) in []: D 2 = Datetime.datetime (8, 8, 790945) in []: d2out[24]: Datetime.datetime (2014, 8, 15, 8, 12, 34, 790945) 2.datetime.datetime.now ([TZ]) When you do not specify a time zone, and Datetime.datetime.today () are the same results as in [+]: Datetime.datetime.now () out[25]: Datetime.datetime (8, 8, 738672) 3..datetime.datetime.strftime (format) formatted to take time, such as "year-month-day hours: minutes: Seconds" Format in [d1out[27]: Datetime.datetime (8, 8, A, 790945) in []: D1.strftime ('%y-%m-%d%h:%m:%s ') out[28]: ' 2014-08-15 08:12:34 ' 4.datetime.datetime.timple () into the struct_time format, which is passed to Time.mktime (t) and then directly into timestamp format in []: d1out[29]: Datetime.datetime (8, 8, 790945) in [+]: D1.timetuple () out[30]: Time.struct_time (tm_year=2014, tm_mon=8 , tm_mday=15, Tm_hour=8, tm_min=12, tm_sec=34, tm_wday=4, tm_yday=227, Tm_isdst=-1) in [to]: Time.mktime (D1.timetuple ()) out[31]: 1408061554.05.datetime.datetime.replace ( Year, month, day) returns a substituted Date object in [[+]: d1out[32]: Datetime.datetime (8, 8, 790945, D1.replace) in [] year=2000) out[33]: Datetime.datetime (8, 8, 790945) 6.datetime.datetime.fromtimestamp (timestamp) Convert timestamp to DateTime object in [Time.time]: out[34 []: 1408061894.081552In []: Datetime.datetime.fromtimestamp (1408061894) OUT[35]: Datetime.datetime (2014, 8, 15, 8, 18, 14)

4.datetime.timedelta class

没啥好说的,主要做时间的加减法用,如下:In [78]: today = datetime.datetime.today()In [79]: yesterday = today - datetime.timedelta(days=1)In [80]: yesterdayOut[80]: datetime.datetime(2014, 8, 14, 15, 8, 25, 783471)In [81]: todayOut[81]: datetime.datetime(2014, 8, 15, 15, 8, 25, 783471)

The most troublesome time for Python is medicine.

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.