3

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?

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Tony Mathew
  • 880
  • 1
  • 12
  • 35
  • 1
    Possible duplicate of [Convert UTC datetime string to local datetime with Python](https://stackoverflow.com/questions/4770297/convert-utc-datetime-string-to-local-datetime-with-python) – Acccumulation Sep 21 '18 at 21:14
  • @Acccumulation the question that you have tagged has timestamp as datetime object while in my problem, timestamp is string object – Tony Mathew Sep 21 '18 at 21:19
  • @TonyMathew - Sure, but your strings come from the datetime objects. So if you can manipulate the datetime objects correctly, you can then derive the correct strings. – John Y Sep 21 '18 at 21:21

1 Answers1

3

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
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135