最近剛接觸項目組內的python項目,發現全部的時間格式都是用的iso8601,同事美其名曰說是爲了項目的國際化(其實用戶量最多幾百人吧,還都集中在公司內部,哪來的國際化,哈哈哈哈!)。因此決定對該時間格式深刻研究下,發現了python中的dateutil模塊。
DATETIME轉ISO8601格式,直接用isoformat()方法轉便可html
now_time = datetime.now().isoformat()
輸出爲python
2018-12-04T08:44:35.792445
now_date_str = datetime.now().isoformat().split('.')[0] my_format = '%Y-%m-%dT%H:%M:%S' print(datetime.strptime(now_date_str, my_format))
這是python中最經常使用的將字符串轉成時間格式的方法,輸出結果爲學習
2018-12-04 08:44:35
from dateutil.parser import parse timestamp = parse(now_date_str, fuzzy=True) print(timestamp)
輸出結果同上,但這個parse方法中的fuzzy很神奇,能夠模糊匹配時間格式,感興趣的能夠看下源碼哈!網站
today = date.today() my_birthday = date(year=1992, month=3, day=17) print('我已經出生' + str((today - my_birthday).days) + '天')
能夠直接計算我本身出生多少天了,輸出爲code
我已經出生9758天
可是若是我要計算我多大了,也就是出生多少年,會出現什麼狀況呢?orm
Traceback (most recent call last): 2018-12-04 08:57:08 File "F:/pythonProject/testcode/testDate.py", line 27, in <module> print((today-my_birthday).years) 2018-12-04 08:57:08 AttributeError: 'datetime.timedelta' object has no attribute 'years'
很遺憾,報錯了,由於timedelta中沒有獲取年份和月份的方法,因此咱們繼續使用dateutil模塊htm
from dateutil.relativedelta import relativedelta diff = relativedelta(today, my_birthday)
經過輸出能夠發現,咱們能獲取到兩個日期中間相差幾年,幾個月和幾天字符串
relativedelta(years=+26, months=+8, days=+17)
print(diff.years) print(diff.months) print(diff.days)
26 8 17
from dateutil.rrule import rrule, WEEKLY pp(list(rrule(WEEKLY, count=10, dtstart=next_tuesday)))
輸出爲get
[datetime.datetime(2018, 12, 4, 8, 59, 6), datetime.datetime(2018, 12, 11, 8, 59, 6), datetime.datetime(2018, 12, 18, 8, 59, 6), datetime.datetime(2018, 12, 25, 8, 59, 6), datetime.datetime(2019, 1, 1, 8, 59, 6), datetime.datetime(2019, 1, 8, 8, 59, 6), datetime.datetime(2019, 1, 15, 8, 59, 6), datetime.datetime(2019, 1, 22, 8, 59, 6), datetime.datetime(2019, 1, 29, 8, 59, 6), datetime.datetime(2019, 2, 5, 8, 59, 6)]
注意:dtstart必須是是時間格式源碼
更多關於dateutil的例子能夠從如下網站學習
https://dateutil.readthedocs....