获取当前日期和时间
import datetime
now = datetime.datetime.now()
print(type(now)) # <class 'datetime.datetime'>
print(now) # 2021-12-27 17:49:06.588719
print(now.date()) # 2021-12-27
print(now.time()) # 17:49:06.588719
print(now.weekday())# 0
print(now.year) # 2021
print(now.month) # 12
print(now.day) # 27
print(now.hour) # 17
print(now.minute) # 49
print(now.second) # 6
字符串与时间互转
import datetime
s = "2021-12-27 17:54:27"
# 字符串 -> datetime
s1 = datetime.datetime.strptime(s,'%Y-%m-%d %H:%M:%S')
print(type(s1)) #<class 'datetime.datetime'>
print(s1) # 2021-12-27 17:54:27
# datetime -> 字符串
s2 = s1.strftime('%a %b %d %H:%M')
print(type(s2)) # <class 'str'>
print(s2) # Mon Dec 27 17:54
时间戳与时间互转
import datetime
d = datetime.datetime.now()
print(type(d)) # <class 'datetime.datetime'>
print(d) # 2021-12-27 18:05:28.754879
# 时间->时间戳
ts = d.timestamp()
print(type(ts)) # <class 'float'>
print(ts) # 1640599528.754879
# 时间戳->时间
d1 = datetime.datetime.fromtimestamp(ts)
print(type(d1)) # <class 'datetime.datetime'>
print(d1) # 2021-12-27 18:05:28.754879
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。