Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with this tzinfo variable?

I have this line of code:

datetime.datetime.fromtimestamp(0, "<DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 STD>")

And it keeps giving me this error:

TypeError: tzinfo argument must be None or of a tzinfo subclass, not type 'str'

What is tzinfo and where does it go?

like image 724
Zach Gates Avatar asked Apr 14 '14 01:04

Zach Gates


2 Answers

The error is somewhat self-explanatory: tzinfo argument requires a tzinfo object rather than a string. I would advise using pytz, however. pytz is much more robust than the standard library's support for time zones. You can install it with pip install pytz. See the docs for more info.

>>> from datetime import datetime
>>> import pytz
>>> d = datetime.fromtimestamp(0)
>>> pacific = pytz.timezone('US/Pacific')
>>> pacific
<DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 STD>
>>> pacific_date = pacific.localize(d)
>>> pacific_date
datetime.datetime(1969, 12, 31, 17, 0, tzinfo=<DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 STD>)
like image 117
Justin O Barber Avatar answered Oct 28 '22 12:10

Justin O Barber


To convert POSIX timestamp to the local timezone e.g., 'US/Pacific':

from datetime import datetime
import pytz # $ pip install pytz

timestamp = 0 # seconds since the Epoch
local_dt = datetime.fromtimestamp(timestamp, pytz.timezone('US/Pacific'))
like image 39
jfs Avatar answered Oct 28 '22 13:10

jfs