Reputation: 910
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?
Upvotes: 3
Views: 8875
Reputation: 49842
To convert a UTC millisecond timestamp into a timezone aware datetime
, you can do:
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
Upvotes: 3