python开发_python日期操作

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

1 import datetime
2 import time

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

time.strftime

datetime

下面是我做的demo:

 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'))

运行效果:

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
>>> 

 

展开阅读全文

没有更多推荐了,返回首页