计算机网络/计算机科学与应用/系统/运维/开发

Python操作日期


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


只要一个人还有追求,他就没有老。直到后悔取代了梦想,一个人才算老。熬过了必须的苦,才能过上喜欢的生活。

评论

^