Python - converting UTC millisecond timestamp to l

2019-07-17 01:52发布

I have a Unix epoch timestamp in milliseconds and need to get date string in local time.

This is my code:

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()]

The original timestamp and the resulting date, hour and all other values generated from the above functions are in UTC. How can I change my code to get it in local time?

1条回答
疯言疯语
2楼-- · 2019-07-17 02:08

To convert a UTC millisecond timestamp into a timezone aware datetime, you can do:

Code:

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)

Test Code:

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'))

Results:

2018-09-22 15:16:29-07:00
22-09-2018
查看更多
登录 后发表回答