Python--日期常見操作
阿新 • • 發佈:2021-08-07
1.時間戳轉時間
1 import datetime
2
3 print(datetime.datetime.fromtimestamp(1487760447.27658))
2.時間戳轉時間格式
1 import datetime
2
3 print(datetime.datetime.fromtimestamp(1487760447.27658).strftime('%Y-%m-%d %H:%M:%S')
3.字串時間轉換成時間
1 import datetime
2
3 s = "2015-06-15 14:00:00"
4 t = datetime.datetime.strptime(s, '%Y-%m-%d %H:%M:%S')
4.時間轉成字串時間
import datetime
t = datetime.datetime.now()
s = t.strftime('%Y-%m-%d %H:%M:%S')
5.時間轉換成時間戳
1 import time
2 import datetime
3
4 now = datetime.datetime.now()
5 print(time.strftime('%s')) # for python2.x
6 print(datetime.datetime.timestamp(now)) # for python3.x
6.向前/向後若干天
1 import datetime
2
3 from dateutil.relativedelta import relativedelta
4
5 now = datetime.datetime.now()
6 # 相差delay_days
7 delay_days = 5
8 print(now-datetime.timedelta(days=delay_days))
9 # 相差delay_months
10 delay_months = 5
11 print(now-relativedelta(months=delay_months))
6.兩個時間點相差日期
from datetime import datetime
from dateutil.relativedelta import relativedelta
date1 = datetime.strptime('2011-08-15 12:00:00', '%Y-%m-%d %H:%M:%S')
date2 = datetime.strptime('2012-02-15', '%Y-%m-%d')
date_delta = relativedelta(date1, date2)
print date_delta.years, date_delta.months, date_delta.weeks, date_delta.days