检查日期是否在世界某个地方有效

时间:2017-05-10 19:51:38

标签: python date timezone timestamp

如何判断某个时间戳是否仍然存在于全球某个地方?

例如,假设我的时间戳类似于2017年5月10日下午3:49。今天世界上有什么地方是2017年5月10日下午3点49分吗?

3 个答案:

答案 0 :(得分:5)

您可以通过将所有时区的当前时间与提供的时间进行比较来进行检查。

这是一个能为你做到这一点的功能:

import datetime
deviations_from_utc = (-12, -11, -10, -9.5, -9, -8, -7, -6, -5,
                   -4, -3.5, -3, -2, -1, 0, 1, 2, 3, 3.5, 4, 4.5, 5,
                   5.5, 5.75, 6, 6.5, 7, 8, 8.5, 8.75, 9, 9.5, 10, 
                   10.5, 11, 12 , 12.75, 13, 14)
def is_current(t):
    n = datetime.datetime.utcnow()
    provided_time = (t.year, t.month, t.day, t.hour, t.minute)
    for time in deviations_from_utc:
        at = n + datetime.timedelta(hours=time)
        at_time = (at.year, at.month, at.day, at.hour, at.minute)
        if provided_time == at_time:
            return True
    return False

deviations_from_utc包含所使用的utc时间的所有偏差。该列表取自this维基百科文章。

答案 1 :(得分:3)

检查时间戳是否在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

&#13;
&#13;
<script src="//repl.it/embed/IRoE/6.js"></script>
&#13;
&#13;
&#13;

请注意,检查应该是包含在内的。但是由于从生成时间戳到检查其有效性所花费的时间,时间戳几乎不在最新时区的边缘情况可能会出现错误。

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

&#13;
&#13;
<script src="//repl.it/embed/IRoE/8.js"></script>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

使用与UTC的标准差,即最大值+14和最小值-12,您可以比较时间戳并查看时间戳是否在最大值和最小值之间。

from datetime import datetime


def is_valid_time(search_timestamp):
    utc_timestamp = datetime.timestamp(datetime.utcnow())
    max_timestamp = utc_timestamp + (14*60*60)  # max time is utc+14
    min_timestamp = utc_timestamp - (12*60*60)  # min time is utc-12

    # check if time in range
    if min_timestamp <= search_timestamp <= max_timestamp:
        return True
    return False

# Test cases
now = datetime.timestamp(datetime.now())
# false
print(is_valid_time(3))

# false
print(is_valid_time(now + (16*60*60)))

# true
print(is_valid_time(now))