Python datetime模塊的使用示例
更新時間:2021年02月02日 16:58:37 作者:南風(fēng)丶輕語
這篇文章主要介紹了Python datetime模塊的使用示例,幫助大家更好的理解和使用python處理時間,感興趣的朋友可以了解下
1、獲取當(dāng)前年月日時分秒
# -*- encoding=utf-8 -*-
import datetime
now = datetime.datetime.now()
print("now:{}".format(now))
year = now.year
print("year:{}".format(year))
month = now.month
print("month:{}".format(month))
day = now.day
print("day:{}".format(day))
hour = now.hour
print("hour:{}".format(hour))
minute = now.minute
print("minute:{}".format(minute))
second = now.second
print("second:{}".format(second))

2、datetime轉(zhuǎn)為string
# -*- encoding=utf-8 -*-
import datetime
now = datetime.datetime.now()
print('type:{}'.format(type(now)))
print('now datetime:{}'.format(now))
now_string = now.strftime('%Y-%m-%d %H:%M:%S')
print('type:{}'.format(type(now_string)))
print('now string:{}'.format(now_string))

3、string轉(zhuǎn)為datetime
# -*- encoding=utf-8 -*-
import datetime
time_str = '2021-01-28 10:51:26'
time_date = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
print('type:{}'.format(type(time_date)))
print(time_date)

4、時間相加
# -*- encoding=utf-8 -*-
import datetime
time_str = '2021-01-28 10:00:00'
time_date = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
print('原始時間:\t\t\t\t{}'.format(time_date))
add_info = datetime.timedelta(days=1, hours=2, minutes=3, seconds=4)
add_end = time_date + add_info
print('加上1天2個小時3分鐘4秒后:\t{}'.format(add_end))

5、時間相減
①兩個時間差
# -*- encoding=utf-8 -*-
import datetime
time_str = '2021-01-28 10:00:00'
time_date = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
print('原始時間:\t{}'.format(time_date))
time_str = '2021-05-29 12:12:12'
time_date2 = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
print('原始時間2:\t{}'.format(time_date2))
time_date3 = time_date2 - time_date
print('時間差:{}'.format(time_date3))

②減去1天2個小時3分鐘4秒(加負(fù)數(shù))
# -*- encoding=utf-8 -*-
import datetime
time_str = '2021-01-28 10:00:00'
time_date = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
print('原始時間:\t\t\t\t{}'.format(time_date))
add_info = datetime.timedelta(days=-1, hours=-2, minutes=-3, seconds=-4)
add_end = time_date + add_info
print('減去1天2個小時3分鐘4秒后:\t{}'.format(add_end))

以上就是Python datetime模塊的使用示例的詳細(xì)內(nèi)容,更多關(guān)于Python datetime模塊的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Caffe均值文件mean.binaryproto轉(zhuǎn)mean.npy的方法
今天小編就為大家分享一篇Caffe均值文件mean.binaryproto轉(zhuǎn)mean.npy的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07
python http服務(wù)flask架構(gòu)實用代碼詳解分析
本篇文章主要分享一個python的簡單http服務(wù)flask架構(gòu)。目前主流的python的服務(wù)框架有django、flask,相較于django來說,flask更小巧玲瓏。至于并發(fā)的問題,使用了gevent協(xié)程io進行處理2021-10-10
基于python和flask實現(xiàn)http接口過程解析
這篇文章主要介紹了基于python和flask實現(xiàn)http接口過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-06-06
Python 數(shù)據(jù)處理庫 pandas進階教程
在前面一篇文章中,我們對pandas做了一些入門介紹。本文是它的進階篇。在這篇文章中,我們會講解一些更深入的知識2018-04-04

