Search code examples
pythondatetimepython-datetimepytz

Display unix time in specific timezone in AM/PM format in Python


I have a large spreadsheet of unix times and corresponding timezones. Row 1 column 1 may be 1538082000 and column 2 would be America/New_York, row 2 may be 1538083000 and America/Los_Angeles. In each case I need them in the format of the time it'd be for someone inside of that timezone.

For example, in my EDT example (row 1) I'd want Sept 27, 2018 5:00:00PM EDT and for row 2 I'd want Sept 27, 2018 2:16:40PM PDT.

I run into this every so often when trying to scrape data and display it in a more friendly format for 3rd parties and I've never been able to find an especially good way of doing this.


Solution

  • Using Arrow:

    >>> import arrow
    >>> utc =  arrow.Arrow.fromtimestamp(1538082000)
    >>> conv = utc.to('America/New_York')
    >>> conv.format("MMM D, YYYY h:mm:ssA ") + conv.tzname()
    

    Results in: Sep 27, 2018 5:00:00PM EDT

    For your second example:

    >>> from dateutil import tz
    >>> t = arrow.Arrow.fromtimestamp(1538083000, tzinfo=tz.gettz("America/Los_Angeles"))
    >>> t.format("MMM D, YYYY h:mm:ssA ") + t.tzname()
    

    Results in Sep 27, 2018 2:16:40PM PDT.

    You can either use the first form using to or you can pass tzinfo to fromtimestamp like in the second example. Personally, I think that the first form looks cleaner.