0

I have time since epoch and I am converting it to datetime.

import datetime
s = '1346114717'
t = datetime.datetime.fromtimestamp(float(s))

is this correct? t is in which timezone? How can I convert it to PST/PDT

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
Alok
  • 35
  • 5

2 Answers2

1

Assuming your string represents Unix time / seconds since 1970-1-1, it refers to UTC. You can convert it to datetime like

from datetime import datetime, timezone

s = '1346114717'
dt = datetime.fromtimestamp(int(s), tz=timezone.utc)

print(dt.isoformat())
# 2012-08-28T00:45:17+00:00

Note that if you don't supply a time zone, the resulting datetime object will be naive, i.e. does not "know" of a time zone. Python will treat it as local time by default (your machine's OS setting).

To convert to US/Pacific time, you can use zoneinfo from Python 3.9's standard lib:

from zoneinfo import ZoneInfo

dt_pacific = dt.astimezone(ZoneInfo('US/Pacific'))
print(dt_pacific.isoformat())
# 2012-08-27T17:45:17-07:00

or use dateutil with older versions of Python:

from dateutil.tz import gettz # pip install python-dateutil

dt_pacific = dt.astimezone(gettz('US/Pacific'))
print(dt_pacific.isoformat())
# 2012-08-27T17:45:17-07:00
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • Wow, it's the first time I see `zoneinfo`. Yet another Python datetime builtin util. I don't know what to think about it. Thanks for adding an example with that. – Tom Wojcik Jan 12 '21 at 09:26
  • @TomWojcik: `zoneinfo` was introduced by [PEP 615](https://www.python.org/dev/peps/pep-0615/) just recently. You can also use it with older Python versions via the [backports module](https://pypi.org/project/backports.zoneinfo/). It really was about time that time zone handling got built into Python I think. – FObersteiner Jan 12 '21 at 09:43
0

python datetime is by default time zone unaware(it doesnt have any timezone information). u could make it aware by using pytz. but i would suggest u take a look at a library like arrow which makes things easier.