datetimeモジュール - Pythonのビルトインモジュール入門

datetimeモジュール - Pythonのビルトインモジュール入門

1、日時モジュール

from datetime import datetime

(1)datetime.now()現在の日付と時刻を取得します

print(datetime.now())  # 获取当前时间

(2)指定された時間と日付を取得します

dt = datetime(2018,5,20,13,14)
print(dt)

(3)指定した時間

current_time = datetime.datetime.now()
print(current_time.replace(year=1977))  # 直接调整到1977年
print(current_time.replace(month=1))  # 直接调整到1月份
print(current_time.replace(year=1989,month=4,day=25))  # 1989-04-25 18:49:05.898601

(4)時間差を探します

print(datetime(2018,10,1,10,11,12) - datetime(2011,11,1,20,10,10))

(5)datetime.timestamp()タイムスタンプにオブジェクトを変換します

d = datetime.now()
print(d.timestamp())

(6)datetime.fromtimestampを()タイムスタンプオブジェクトを変換します

import time
f_t = time.time()
print(datetime.fromtimestamp(f_t))

(7)文字列にオブジェクトをdatetime.strftime

d = datetime.now()
print(d.strftime("%Y-%m-%d %H:%M:%S"))

(8)ターゲットにdatetime.strptimeストリング

s = "2018-12-31 10:11:12"
print(datetime.strptime(s,"%Y-%m-%d %H:%M:%S"))

(9)加算および減算することができ

from datetime import datetime,timedelta
print(datetime.now() - timedelta(days=1))
print(datetime.now() - timedelta(hours=1))

おすすめ

転載: www.cnblogs.com/caiyongliang/p/11490818.html