Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python time utils
import datetime
import pytz
# careful, don't assume now() is nyc time! on ec2, it's utc time.
def datetime_from_tz_naive_nyc_to_tz_aware_utc(nyc_datetime_tz_naive):
nyc_datetime_tz_aware = pytz.timezone('US/Eastern').localize(nyc_datetime_tz_naive)
return nyc_datetime_tz_aware.astimezone(pytz.utc)
def utc_tz_aware(utc_datetime_tz_naive):
return pytz.timezone('UTC').localize(utc_datetime_tz_naive)
def utcnow_tz_aware():
utcnow_tz_naive = datetime.datetime.utcnow()
return utc_tz_aware(utcnow_tz_naive)
def seconds_until_utc_time(utc_datetime_later):
# utc_datetime_now = datetime_from_tz_naive_nyc_to_tz_aware_utc(datetime.datetime.now())
utc_datetime_now = utcnow_tz_aware()
datetime_diff_timedelta = utc_datetime_later - utc_datetime_now
# can be negative, if "later" is actually in the past!
seconds_until_later = datetime_diff_timedelta.days * 86400 + datetime_diff_timedelta.seconds
return seconds_until_later
def get_utc_datetime_n_secs_in_future(n_secs):
return (utcnow_tz_aware() + datetime.timedelta(seconds=n_secs))
# ISO format to expect: 2017-08-24T09:47:57.883578-00:00
# drop microseconds and timezone; assume UTC
def strptime_utc_to_tz_aware_utc(utc_datetime_str):
try:
utc_datetime_tz_naive = datetime.datetime.strptime(utc_datetime_str[0:19], '%Y-%m-%dT%H:%M:%S')
except:
try:
utc_datetime_tz_naive = datetime.datetime.strptime(utc_datetime_str[0:19], '%Y-%m-%d %H:%M:%S')
except:
return None
return utc_tz_aware(utc_datetime_tz_naive)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment