-
Notifications
You must be signed in to change notification settings - Fork 51
Python datetime
jiaxw32 edited this page Jun 30, 2020
·
2 revisions
from datetime import datetime
# current date
now = datetime.now()
print(f"object value: {now}, class type: {type(now)}")
# current timestamp
timestamp = datetime.timestamp(now)
print(timestamp)
# year、month、day、hour、minute、second
year = now.year
month = now.month
day = now.day
hour = now.hour
minute = now.minute
second = now.second
print(f"year = {year}, month = {month}, day = {day}, hour = {hour}, minute = {minute}, second = {second}")
from datetime import datetime
timestamp = 1593517387.454917
dt_object = datetime.fromtimestamp(timestamp)
print("dt_object =", dt_object)
print("type(dt_object) =", type(dt_object))
from datetime import datetime
# current date and time
now = datetime.now()
timestamp = datetime.timestamp(now)
print("timestamp =", timestamp)
from datetime import datetime
now = datetime.now()
text = now.strftime('%Y-%m-%d %H:%M:%S')
print(text)
from datetime import datetime
text = '2020-06-30'
date = datetime.strptime(text, '%Y-%m-%d')
print(date)
strptime()
的性能要比你想象中的差很多, 因为它是使用纯Python实现,并且必须处理所有的系统本地设置。 如果你要在代码中需要解析大量的日期并且已经知道了日期字符串的确切格式,可以自己实现一套解析方案,来获取更好的性能。