Python里面用来管理时间的模块有2个,分别是time模块和datetime模块,现在看看如何使用
首先看看time模块
例1
1
2
3
4
|
import time
print (time.time()) #时间戳,1970年到现在的秒数
- - - - - - - - - - - - - - - - - - -
1474347039.991068 |
例2
1
2
3
|
print (time.ctime()) #当前系统时间字符串格式
- - - - - - - - - - - - - - - - - - -
Tue Sep 20 14 : 50 : 39 2016
|
例3
1
2
3
|
print (time.ctime(time.time() - 86400 )) #根据时间戳算时间
- - - - - - - - - - - - - - - - - - - - -
Mon Sep 19 14 : 50 : 39 2016
|
例4
1
2
3
4
5
6
7
8
|
#显示的是格林威治时间 print (time.gmtime())
time_obj = time.gmtime()
print (time_obj.tm_year,time_obj.tm_mon)
- - - - - - - - - - - - - - - - - - - - -
time.struct_time(tm_year = 2016 , tm_mon = 9 , tm_mday = 20 , tm_hour = 4 , tm_min = 50 , tm_sec = 39 , tm_wday = 1 , tm_yday = 264 , tm_isdst = 0 )
2016 9
|
例5
1
2
3
4
|
#显示本地时间 print (time.localtime())
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
time.struct_time(tm_year = 2016 , tm_mon = 9 , tm_mday = 20 , tm_hour = 14 , tm_min = 50 , tm_sec = 39 , tm_wday = 1 , tm_yday = 264 , tm_isdst = 0 )
|
例6
1
2
3
4
|
#必须传入一个时间对象的参数,把structure time转换成时间戳 print (time.mktime(time_obj))
- - - - - - - - - - - - - - - - - - - - -
1474311039.0 |
例7
1
2
|
#延时多少秒 time.sleep( 4 )
|
例8
1
2
3
4
|
#把时间对象转成字符串格式 print (time.strftime( "%Y-%m-%d %H:%M:%S" ,time_obj))
- - - - - - - - - - - - - - - - - - - -
2016 - 09 - 20 04 : 50 : 39
|
例9
1
2
3
4
5
6
7
|
#把字符串格式转换为时间对象 tm = time.strptime( "2016-05-10 15:04:20" , "%Y-%m-%d %H:%M:%S" )
print (tm)
print (time.mktime(tm))
- - - - - - - - - - - - - - - - - - - - -
time.struct_time(tm_year = 2016 , tm_mon = 5 , tm_mday = 10 , tm_hour = 15 , tm_min = 4 , tm_sec = 20 , tm_wday = 1 , tm_yday = 131 , tm_isdst = - 1 )
1462856660.0 |
接下来看看datetime模块
例1
1
2
3
4
|
import datetime
print (datetime.date.today()) #输出当前日期
- - - - - - - - - - - -
2016 - 09 - 20
|
例2
1
2
3
4
|
currenttime = datetime.datetime.now() #输出当前时间,最常用
print (currenttime)
- - - - - - - - - - - -
2016 - 09 - 20 14 : 50 : 44.018886
|
例3
1
2
3
4
|
#比当前时间加10天 new_date = datetime.date.today() + datetime.timedelta(days = 10 )
print (new_date)
2016 - 09 - 30
|
例4
1
2
3
4
5
|
#比当前时间少1个小时 new_date = datetime.datetime.now() + datetime.timedelta(hours = - 1 )
print (new_date)
- - - - - - - - - - - -
2016 - 09 - 20 13 : 50 : 44.018923
|
例5
#直接替换
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
print (currenttime.replace( 2014 , 9 , 12 ))
- - - - - - - - -
2014 - 09 - 12 14 : 50 : 44.018886
print (currenttime.replace(year = 2015 ))
- - - - - - - - -
2015 - 09 - 20 14 : 50 : 44.018886
time_obj = currenttime.replace( 2015 )
print (time_obj, type (time_obj))
- - - - - - - - - - -
2015 - 09 - 20 14 : 50 : 44.018886 < class 'datetime.datetime' >
print (currenttime>time_obj)
- - - - - - - - - - -
True |
本文转自 beanxyz 51CTO博客,原文链接:http://blog.51cto.com/beanxyz/1854443,如需转载请自行联系原作者