如何检查给定的时间戳是否仍然存在于全球的某个地方?
例如,假设我的时间戳类似于2017年5月10日下午3:49.今天世界上有什么地方是2017年5月10日下午3:49吗?
解决方法:
检查时间戳是否在UTC 14和UTC-12之间.
from datetime import datetime, timedelta
def is_a_today_somewhere(timestamp):
now = datetime.now()
latest = now + timedelta(hours=-12)
earliest = now + timedelta(hours=14)
return latest <= datetime.fromtimestamp(timestamp) <= earliest
now = datetime.now() # now
timestamp = datetime.timestamp(now)
print(is_a_today_somewhere(timestamp)) # prints True
now = datetime.now() + timedelta(hours=7) # +7 hours from now
timestamp = datetime.timestamp(now)
print(is_a_today_somewhere(timestamp)) # prints True
now = datetime.now() + timedelta(hours=-23) # -23 hours from now
timestamp = datetime.timestamp(now)
print(is_a_today_somewhere(timestamp)) # prints False
请注意,检查应该是包含在内的.但是由于从生成时间戳到检查其有效性所花费的时间,时间戳几乎不在最新时区的边缘情况可能会出现错误.
from datetime import datetime, timedelta
def is_a_today_somewhere(timestamp):
now = datetime.now()
latest = now + timedelta(hours=-12)
earliest = now + timedelta(hours=14)
return latest <= datetime.fromtimestamp(timestamp) <= earliest
now = datetime.now() + timedelta(hours=-12) # -12 hours from now; barely in today
timestamp = datetime.timestamp(now)
print(is_a_today_somewhere(timestamp)) # May print False
标签:python,date,timezone,timestamp
来源: https://codeday.me/bug/20190722/1501385.html