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
添加回答
舉報