我有一个以毫秒为单位的 Unix 纪元时间戳,需要获取本地时间的日期字符串。
这是我的代码:
date = datetime.utcfromtimestamp(timestamp / 1000).strftime('%d-%m-%Y')
hour = datetime.utcfromtimestamp(timestamp / 1000).strftime('%H')
month = datetime.utcfromtimestamp(timestamp / 1000).strftime('%m')
monthName = calendar.month_name[int(month)]
weekDay = calendar.day_name[(datetime.strptime(date, '%d-%m-%Y')).weekday()]
原始时间戳和结果日期、小时以及从上述函数生成的所有其他值均采用 UTC。如何更改我的代码以在本地时间获取它?
最佳答案
要将 UTC 毫秒时间戳转换为可识别时区的 datetime
,您可以执行以下操作:
代码:
def tz_from_utc_ms_ts(utc_ms_ts, tz_info):
"""Given millisecond utc timestamp and a timezone return dateime
:param utc_ms_ts: Unix UTC timestamp in milliseconds
:param tz_info: timezone info
:return: timezone aware datetime
"""
# convert from time stamp to datetime
utc_datetime = dt.datetime.utcfromtimestamp(utc_ms_ts / 1000.)
# set the timezone to UTC, and then convert to desired timezone
return utc_datetime.replace(tzinfo=pytz.timezone('UTC')).astimezone(tz_info)
测试代码:
import datetime as dt
import pytz
utc_ts = 1537654589000
utc_time = "Sat Sep 22 22:16:29 2018 UTC"
pdt_time = "Sat Sep 22 15:16:29 2018 PDT"
tz_dt = tz_from_utc_ms_ts(utc_ts, pytz.timezone('America/Los_Angeles'))
print(tz_dt)
print(tz_dt.strftime('%d-%m-%Y'))
结果:
2018-09-22 15:16:29-07:00
22-09-2018
关于Python - 将 UTC 毫秒时间戳转换为本地时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52451105/