Getting Started with Python's built-in module - datetime module

Getting Started with Python's built-in module - datetime module

1, datetime module

from datetime import datetime

(1) datetime.now () to get the current time and date

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

(2) to obtain a specified time and date

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

(3) a specified time

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) Find the time difference

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

(5) datetime.timestamp () to convert an object into a timestamp

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

(6) datetime.fromtimestamp () to convert a timestamp object

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

(7) datetime.strftime the object into a string

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

(8) datetime.strptime string into the target

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

(9) can add and subtract

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

Guess you like

Origin www.cnblogs.com/caiyongliang/p/11490818.html