Python--日期常见操作
2021/8/7 11:35:57
本文主要是介绍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--日期常见操作的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-14获取参数学习:Python编程入门教程
- 2024-11-14Python编程基础入门
- 2024-11-14Python编程入门指南
- 2024-11-13Python基础教程
- 2024-11-12Python编程基础指南
- 2024-11-12Python基础编程教程
- 2024-11-08Python编程基础与实践示例
- 2024-11-07Python编程基础指南
- 2024-11-06Python编程基础入门指南
- 2024-11-06怎么使用python 计算两个GPS的距离功能-icode9专业技术文章分享