Check if the date is valid somewhere in the world
3 answers
Check if there is a timestamp between UTC + 14 and 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
Please note that verification must be enabled. But due to the time it takes to create a timestamp to validate it, edge cases where the timestamp is barely in the last timezone can appear 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
+3
source to share
You can check by comparing the current time in all time zones with the time provided.
Here's a function to do it for you:
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 contains all deviations from utc times that are in use. The list was taken from this wikipedia article.
+5
source to share
By using the standard deviations from UTC ie a maximum of +14 and a minimum of -12, you can compare the timestamps and see if the timestamp is between the maximum and minimum.
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))
+1
source to share