我正在编写一种返回时区的方法,即具有不同日期的UTC时区。此方法应采用用户设置为输入的时区。我知道我必须越过国际日期线才能到达不同日期的时区,但我不确定我是否在这里遗漏了一些东西。 例如如果我在EST时区,则返回日期与EST时区不同的时区。
public String getDifferentDate (String timeZone) {
//Calculate the time zone offset required to cross International Date line
//RETURN newTimeZone with different date.
}
答案 0 :(得分:2)
获取某个时区,其中日期与给定时区中的当前日期不同:
#!/usr/bin/env python
from datetime import datetime
import pytz # $ pip install pytz
def get_timezone_with_different_date(input_timezone_id, now=None):
"""
input_timezone_id: the tz database id such as 'America/New_York'
now: a naive datetime object representing time in input_timezone_id
"""
input_tz = pytz.timezone(input_timezone_id)
if now is None:
now = datetime.now(input_tz) # use the current time
else:
now = input_tz.localize(now, is_dst=None) # make it timezone-aware
for tz in map(pytz.timezone, pytz.all_timezones_set):
if tz.normalize(now.astimezone(tz)).date() != now.date():
return tz.zone
assert 0, 'never happens'
示例:
>>> get_timezone_with_different_date('US/Eastern')
'Australia/Melbourne'
注意:一般情况下,您无需越过国际日期行即可获得不同的日期。