python datetime庫使用和時間加減計算


datetime庫使用

一、操作當前時間

1.獲取當前時間

>>> import datetime
>>> print datetime.datetime.now()
2019-07-11 14:24:01.954000

時間格式化輸出:

>>> print datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
2019-07-11 14:25:33
>>> print datetime.datetime.now().strftime("%Y%m%d")
20190711
>>> print datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
2019-07-11 14:25

使用timedelta方法對當前時間進行加減

加 一分鍾

>>> print (datetime.datetime.now()+datetime.timedelta(minutes=1)).strftime("%Y-%m-%d %H:%M:%S")
2019-07-11 14:29:46

減 一分鍾

>>> print (datetime.datetime.now()+datetime.timedelta(minutes=-1)).strftime("%Y-%m-%d %H:%M:%S")
2019-07-11 14:29:32

加 一天

>>> print (datetime.datetime.now()+datetime.timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%S")
2019-07-12 14:32:37

加 一小時

>>> print (datetime.datetime.now()+datetime.timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S")
2019-07-11 15:33:37

也可以使用timedelta方法對指定時間進行加減:首先對指定時間進行處理

strTime = '2019-07-11 11:03'  # 給定一個時間,此是個字符串
startTime = datetime.datetime.strptime(strTime, "%Y-%m-%d %H:%M")  # 把strTime轉化為時間格式,后面的秒位自動補位的
print startTime
print startTime.strftime("%Y-%m-%d %H:%M")  # 格式化輸出,保持和給定格式一致
# startTime時間加 一分鍾
startTime2 = (startTime + datetime.timedelta(minutes=2)).strftime("%Y-%m-%d %H:%M")
print startTime2

輸出:

2019-07-11 11:03:00
2019-07-11 11:03
2019-07-11 11:05

Process finished with exit code 0

 循環加時間

startTime = '2019-07-11 23:30:00'  # 輸入一個時間,此是個字符串
# endTime = '2019-07-11 15:35'
for i in range(3):
    endTime = (datetime.datetime.strptime(startTime, "%Y-%m-%d %H:%M:%S") + datetime.timedelta(
        days=1)).strftime("%Y-%m-%d %H:%M:%S")
    print startTime,endTime
    startTime = endTime

# 參數days=1(天+1) 可以換成 minutes=1(分鍾+1)、seconds=1(秒+1)
輸出:
2019-07-11 23:30:00 2019-07-12 23:30:00
2019-07-12 23:30:00 2019-07-13 23:30:00
2019-07-13 23:30:00 2019-07-14 23:30:00

Process finished with exit code 0

 





免責聲明!

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



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