[英]Convert US/Eastern to UTC including daylight savings Python
I was really surprised to not find an easy way to do this in Python.我真的很惊讶没有在 Python 中找到一种简单的方法来做到这一点。 We wrote this in December and it passed, because it was winter:
我们在 12 月写了这个,它通过了,因为那是冬天:
def get_utc_time(dt_or_str, number_of_days=None, time_format=DATETIME_FORMAT):
"""
:param dt_or_str:
:return:
"""
eastern = pytz.timezone('US/Eastern')
# try:
if isinstance(dt_or_str, datetime):
new_date_str = dt_or_str.strftime(time_format)
new_date_obj = dt_or_str
else:
new_date_str = dt_or_str
new_date_obj = datetime.strptime(dt_or_str, time_format)
if not number_of_days:
utc_time = eastern.localize(
datetime.strptime(new_date_str, time_format),
is_dst=None).astimezone(pytz.utc)
else:
est_time = new_date_obj - timedelta(days=number_of_days)
utc_time = eastern.localize(est_time, is_dst=None).astimezone(pytz.utc)
utc_time = utc_time.replace(tzinfo=None)
What this did is add 5 hours to your time to make it UTC.这样做是为您的时间增加了 5 小时,使其成为 UTC。 It turns out in Spring/Summer Eastern time is only 4 hours behind UTC, so our code is now broken.
事实证明,春季/夏季东部时间仅比 UTC 晚 4 小时,因此我们的代码现在已损坏。
This is the test we wrote that does not work in Summer:这是我们写的在 Summer 不起作用的测试:
def test_get_utc_time_incoming_string(self):
result = get_utc_time("2017-02-02 04:38")
self.assertEqual(result, datetime.datetime(2017, 2, 2, 8, 38))
How can you convert EST to UTC that will work year round?您如何将 EST 转换为全年可用的 UTC? I don't want to hard code it since daylight savings period changes each year.
我不想硬编码它,因为夏令时每年都在变化。
Found this on an answer:在一个答案中找到了这个:
def is_daylight_savings(timezone_name):
tz = pytz.timezone(timezone_name)
now = pytz.utc.localize(datetime.utcnow())
return now.astimezone(tz).dst() != timedelta(0)
so now this:所以现在这个:
def get_utc_time(dt_or_str, number_of_days=None, time_format=DATETIME_FORMAT):
"""
:param dt_or_str:
:return:
"""
eastern = pytz.timezone(TIMEZONE)
it_is_daylight_savings = is_daylight_savings(TIMEZONE)
if isinstance(dt_or_str, datetime):
new_date_str = dt_or_str.strftime(time_format)
new_date_obj = dt_or_str
else:
new_date_str = dt_or_str
new_date_obj = datetime.strptime(dt_or_str, time_format)
if not number_of_days:
utc_time = eastern.localize(
datetime.strptime(new_date_str, time_format),
is_dst=it_is_daylight_savings).astimezone(pytz.utc)
else:
est_time = new_date_obj - timedelta(days=number_of_days)
utc_time = eastern.localize(est_time, is_dst=it_is_daylight_savings).astimezone(pytz.utc)
utc_time = utc_time.replace(tzinfo=None)
return utc_time
as freedom of speech dies, freedom to be rude increases exponentionally随着言论自由的消亡,粗鲁的自由呈指数增长
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.