Let's say I have a variable t that's set to this:
datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=<UTC>)
If I say str(t)
, i get:
'2009-07-10 18:44:59.193982+00:00'
How can I get a similar string, except printed in the local timezone rather than UTC?
Think your should look around: datetime.astimezone()
http://docs.python.org/library/datetime.html#datetime.datetime.astimezone
Also see pytz module - it's quite easy to use -- as example:
http://pytz.sourceforge.net/
Example:
As of python 3.2, using only standard library functions:
Just need to use
l_tm - u_tm
oru_tm - l_tm
depending whether you want to show as + or - hours from UTC. I am in MST, which is where the -07 comes from. Smarter code should be able to figure out which way to subtract.And only need to calculate the local timezone once. That is not going to change. At least until you switch from/to Daylight time.
I believe the best way to do this is to use the
LocalTimezone
class defined in thedatetime.tzinfo
documentation (goto http://docs.python.org/library/datetime.html#tzinfo-objects and scroll down to the "Example tzinfo classes" section):Assuming
Local
is an instance ofLocalTimezone
then
str(local_t)
gives:which is what you want.
(Note: this may look weird to you because I'm in New South Wales, Australia which is 10 or 11 hours ahead of UTC)
I use this function
datetime_to_local_timezone()
, which seems overly convoluted but I found no simpler version of a function that converts adatetime
instance to the local time zone, as configured in the operating system, with the UTC offset that was in effect at that time:This example prints four dates. For two moments in time, one in January and one in July 2009, each, it prints the timestamp once in UTC and once in the local time zone. Here, where CET (UTC+01:00) is used in the winter and CEST (UTC+02:00) is used in the summer, it prints the following:
I wrote something like this the other day:
So the interesting part for you is probably the line starting with "mytz=...". time.timezone returns the local timezone, albeit with opposite sign compared to UTC. So it says "-3600" to express UTC+1.
Despite its ignorance towards Daylight Saving Time (DST, see comment), I'm leaving this in for people fiddling around with
time.timezone
.