python判断输入日期是否有效_python – 检查日期是否在世界某个地方有效

如何检查给定的时间戳是否仍然存在于全球的某个地方?

例如,假设我的时间戳类似于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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值