前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python开发_python日期操作

python开发_python日期操作

作者头像
Hongten
发布2018-09-13 13:48:52
8230
发布2018-09-13 13:48:52
举报
文章被收录于专栏:HongtenHongten

在python中对日期进行操作的库有:

代码语言:javascript
复制
1 import datetime
2 import time

对日期格式化信息,可以参考官方API:

time.strftime

datetime

下面是我做的demo:

代码语言:javascript
复制
 1 #datetime
 2 
 3 import datetime
 4 
 5 #当前日期
 6 now = datetime.datetime.now()
 7 print(now.strftime('%Y-%m-%d %H:%M:%S'))
 8 print(now.strftime('%Y-%m-%d'))
 9 
10 #string convert to datetime
11 time_str = '2013-07-29 01:05:00'
12 str_convert_2_time = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
13 print(str_convert_2_time)
14 
15 #比较两个日期相差多少天
16 time_strA = '2013-07-29 01:05:00'
17 time_strB ='2013-08-29 01:05:00' 
18 day = datetime.datetime.strptime(time_strA, '%Y-%m-%d %H:%M:%S')
19 day2 = datetime.datetime.strptime(time_strB, '%Y-%m-%d %H:%M:%S')
20 sub_day = day2 - day
21 print('{0}和{1}相差{2}天'.format(time_strA, time_strB, str(sub_day.days)))
22 
23 
24 #今后的n天的日期
25 n_days = 4
26 now = datetime.datetime.now()
27 my_date = datetime.timedelta(days=n_days)  
28 n_day = now + my_date
29 print('从今天起的{0}天的日期是:'.format(n_days))
30 print(n_day.strftime('%Y-%m-%d %H:%M:%S'))

运行效果:

代码语言:javascript
复制
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
2013-07-29 01:48:16
2013-07-29
2013-07-29 01:05:00
2013-07-29 01:05:00和2013-08-29 01:05:00相差31天
从今天起的4天的日期是:
2013-08-02 01:48:16
>>> 
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2013-07-29 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档