time.strptime():
將普通字符時間轉換爲時間元祖,注意這兩者在轉換時需要指定字符時間的格式(%Y%m%d
這裏只用到了年月日)
import time
print time.strptime('20170301', '%Y%m%d')
輸出結果:
time.struct_time(tm_year=2017, tm_mon=3, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=60, tm_isdst=-1)
time.mktime():
將上一步的時間元祖轉換爲時間戳,即1970年0時0分0秒到20170301的0時0分0秒爲止,過了多少秒
import time
print time.mktime(time.strptime('20170301','%Y%m%d'))
輸出結果:
1488297600.0
time.localtime():
將時間戳轉換爲時間元祖
import time
print time.localtime(1488297600.0)
輸出結果:
time.struct_time(tm_year=2017, tm_mon=3, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=60, tm_isdst=0)
time.strftime:
將時間元祖復原爲普通字符時間,同樣注意需要指定字符時間的格式
import time
print time.strftime('%Y%m%d',time.localtime(1488297600.0))
輸出結果:
20170301
求當前時間:datetime.now()
from datetime import datetime, timedelta
print datetime.now()
print (datetime.now()).strftime('%Y%m%d')
print (datetime.now()).strftime('%Y/%m/%d %H:%M:%S')
輸出結果:
2017-03-01
09:48:23.104000
20170301
2017/03/01 09:48:23
時間運算:timedelta(weeks, days, hours, second, milliseconds, microseconds) ,參數可選,默認爲0
from datetime import datetime, timedelta
print (datetime.now()-timedelta(days=1)).strftime('%Y%m%d') # 1天前的日期
print (datetime.now()+timedelta(days=100)).strftime('%Y%m%d') # 100天后的日期
print (datetime.now()-timedelta(hours=1)).strftime('%Y/%m/%d %H:%M:%S') #求一小時前的時間
輸出結果:
20170228201706092017/03/01 08:42:45
字符時間常用格式:
%Y Year with century as a decimal number.
%m Month as a decimal number [01,12].
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%M Minute as a decimal number [00,59].
%S Second as a decimal number [00,59].
%z Time zone offset from UTC.
%a Locale's abbreviated weekday name.
%A Locale's full weekday name.
%b Locale's abbreviated month name.
%B Locale's full month name.
%c Locale's appropriate date and time representation.
%I Hour (12-hour clock) as a decimal number [01,12].
%p Locale's equivalent of either AM or PM.
from datetime import datetime
print (datetime.now()).strftime('%Y')
print (datetime.now()).strftime('%m')
print (datetime.now()).strftime('%d')
print (datetime.now()).strftime('%H')
print (datetime.now()).strftime('%M')
print (datetime.now()).strftime('%S')
print (datetime.now()).strftime('%a')
print (datetime.now()).strftime('%A')
print (datetime.now()).strftime('%b')
print (datetime.now()).strftime('%B')
print (datetime.now()).strftime('%c')
print (datetime.now()).strftime('%I')
print (datetime.now()).strftime('%p')
輸出結果:
2017
03
01
09
56
30
Wed
Wednesday
Mar
March
03/01/17 09:56:30
09
AM