datetime与timestamp
from datetime import datetime
now = datetime.now()
print(now)
#日期转时间戳
timestamp = now.timestamp()
print(timestamp,type(timestamp))
#时间戳转日期
c2=datetime.fromtimestamp(timestamp)
print(c2,type(c2))
...
2020-05-22 11:04:35.606201
1590116675.606201 <class 'float'>
2020-05-22 11:04:35.606201 <class 'datetime.datetime'>
datetime与str
from datetime import datetime
# 字符串转日期
cday = datetime.strptime('2015-6-1 18:19:59', '%Y-%m-%d %H:%M:%S') #
print(cday)
print(type(cday))
# 日期转字符串
sday=cday.strftime( '%Y-%m-%d %H:%M:%S')
print(sday)
print(type(sday))
...
2015-06-01 18:19:59
<class 'datetime.datetime'>
2015-06-01 18:19:59
<class 'str'>
日期加减
>>> from datetime import datetime, timedelta
>>> now = datetime.now()
>>> now
datetime.datetime(2015, 5, 18, 16, 57, 3, 540997)
>>> now + timedelta(hours=10)
datetime.datetime(2015, 5, 19, 2, 57, 3, 540997)
>>> now - timedelta(days=1)
datetime.datetime(2015, 5, 17, 16, 57, 3, 540997)
>>> now + timedelta(days=2, hours=12)
datetime.datetime(2015, 5, 21, 4, 57, 3, 540997)
网友评论