Python教程

Python--日期常见操作

本文主要是介绍Python--日期常见操作,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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
这篇关于Python--日期常见操作的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!