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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM