3 回答
TA贡献1825条经验 获得超4个赞
不使用 Arrow 的解决方案。
from datetime import datetime
from pytz import timezone
def convert_time(timestamp, tz):
tzinfo = timezone(tz)
dt = datetime.fromtimestamp(timestamp)
fmt = "%b %d, %Y %-I:%M:%S%p "
return dt.astimezone(tzinfo).strftime(fmt) + tzinfo.tzname(dt)
>>> ts = "1538082000"
>>> tz = "America/New_York"
>>> convert_time(int(ts), tz)
>>> Sep 27, 2018 5:00:00PM EDT
>>> ts2 = "1538083000"
>>> tz2 = "America/Los_Angeles"
>>> convert_time(int(ts2), tz2)
>>> Sep 27, 2018 2:16:40PM PDT
TA贡献1887条经验 获得超5个赞
使用%I会将 Hour 格式化为12-hour time,%p并将返回AM/PM.
使用pytz也可以:
from datetime import datetime
import pytz
def convert_time(timestamp, tz):
eastern = pytz.timezone('UTC')
tzinfo = pytz.timezone(tz)
loc_dt = eastern.localize(datetime.utcfromtimestamp(timestamp))
fmt = "%b %d, %Y %I:%M:%S%p %Z"
return loc_dt.astimezone(tzinfo).strftime(fmt)
ts = "1538082000"
tz = "America/New_York"
print(convert_time(int(ts), tz))
>> Sep 28, 2018 05:00:00PM EDT
ts = "1538083000"
tz = "America/Los_Angeles"
print(convert_time(int(ts), tz))
>> Sep 28, 2018 02:16:40PM PDT
添加回答
举报