1

Consider a list of posix time stamps

posix_times = [1490750889, 1490751209, 1490751569]

I would like to convert each element in the array to a text string containing the local date and time in the US/Pacific time zone:

 ["3/28/2017 18:28:09", "3/28/2017 18:33:29", "3/28/2017 18:39:29"]

What is the simplest way to do this which requires a minimum of package imports?

A related problem was addressed in Converting unix timestamp string to readable date in Python, which offers, for example a solution of the form:

posix_time = 1490750889
datetime.datetime.utcfromtimestamp(posix_time).strftime('%Y-%m-%dT%H:%M:%SZ')

which does not offer the explicit ability to convert this time to another time zone. Also, it appears that such a method does not work on lists and would require a for loop/list comprehension.

Community
  • 1
  • 1
rhz
  • 960
  • 14
  • 29
  • 1
    Possible duplicate of [Converting unix timestamp string to readable date in Python](http://stackoverflow.com/questions/3682748/converting-unix-timestamp-string-to-readable-date-in-python) – McGrady Apr 15 '17 at 03:55
  • As indicated in the amended question, I don't believe this is an exact duplicate since I don't see where the collection of solutions you refer to show explicitly how to deal with arbitrary time zone. – rhz Apr 15 '17 at 05:17

2 Answers2

2

You can do this with the standard datetime library:

In [1]: import datetime

In [2]: posix_times = [1490750889, 1490751209, 1490751569]

In [3]: [datetime.datetime.fromtimestamp(x).strftime("%x %X") for x in posix_times]
Out[3]: ['03/28/17 20:28:09', '03/28/17 20:33:29', '03/28/17 20:39:29']
jordanm
  • 33,009
  • 7
  • 61
  • 76
  • I'm confused. How does this know to shift the time to us/pacific? Is that because that is my local time zone? – rhz Apr 15 '17 at 04:32
  • 1
    @rhz yes, it uses your local time zone. – jordanm Apr 15 '17 at 06:12
  • Do you think that there a simple modification of your solution to specify an arbitrary time zone or would this require additional packages like pytz as in Pedro Castilho's solution? – rhz Apr 15 '17 at 07:07
  • @rhz pytz is the easiest way. – jordanm Apr 15 '17 at 17:34
1

You can convert a UNIX timestamp into a datetime object and then format it using its strftime method. However, this will give you a timezone-unaware datetime. In order to make it timezone-aware, you'll need to get the timezone from pytz and use the localize method:

from datetime import datetime
from pytz import timezone

# ...

def format_time(time, tz):
  localized = tz.localize(datetime.fromtimestamp(time))
  return localized.strftime('%d/%m/%Y %H:%M:%S')

us_pacific = timezone('US/Pacific')
dates = map(lambda t: format_time(t, us_pacific), posix_times)
Pedro Castilho
  • 10,174
  • 2
  • 28
  • 39