2018年11月18日 星期日

[ Python 常見問題 ] How to shift a datetime object by 12 hours in python

Source From Here 
Question 
Datetime objects hurt my head for some reason. I am writing to figure out how to shift a date time object by 12 hours. I also need to know how to figure out if two date time object's differ by say 1 minute or more. 

How-To 
The datetime library has a timedelta object specifically for this kind of thing: 
>>> from datetime import datetime 
>>> my_datetime = datetime.now() 
>>> from datetime import timedelta 
>>> twelve_hours_later = my_datetime + timedelta(hours=12) 
>>> twelve_hours_earlier = my_datetime - timedelta(hours=12) 
>>> my_datetime.strftime('%y-%m-%d %H:%M:%S') 
'18-11-18 19:08:54' 

>>> twelve_hours_later.strftime('%y-%m-%d %H:%M:%S') 
'18-11-19 07:08:54' 
>>> twelve_hours_earlier.strftime('%y-%m-%d %H:%M:%S') 
'18-11-18 07:08:54' 
>>> diff = abs(twelve_hours_later - my_datetime) 
>>> abs(twelve_hours_later - my_datetime) 
datetime.timedelta(0, 43200) 
>>> diff.__class__ 
 
>>> if diff.total_seconds() > 60: 
... print("Timestamps were more than a minute apart") 
... 
Timestamps were more than a minute apart 
>>> print("Time diff in {} hours!".format(diff.total_seconds() / 60 / 60)) 
Time diff in 12.0 hours!


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...