tags:

views:

583

answers:

4

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?

+1  A: 

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:

eastern = timezone('US/Eastern')

http://pytz.sourceforge.net/

Mihail
So how do i get the current local timezone?
mike
isn't datetime.datetime(2009, 7, 10, 18, 44, 59, 193982) - what you need?
Mihail
This answer is wrong. I live in England and US/Eastern is NOT the **local** timezone.
Philluminati
@Muhail - No, because the resultant object is not datetime aware. You do not know what timezone you are in.
Philluminati
+1  A: 

I wrote something like this the other day:

import time, datetime
def nowString():
    # we want something like '2007-10-18 14:00+0100'
    mytz="%+4.4d" % (time.timezone / -(60*60) * 100) # time.timezone counts westwards!
    dt  = datetime.datetime.now()
    dts = dt.strftime('%Y-%m-%d %H:%M')  # %Z (timezone) would be empty
    nowstring="%s%s" % (dts,mytz)
    return nowstring

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.

ThomasH
+2  A: 

I believe the best way to do this is to use the LocalTimezone class defined in the datetime.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 of LocalTimezone

t = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=utc)
local_t = t.astimezone(Local)

then str(local_t) gives:

'2009-07-11 04:44:59.193982+10:00'

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)

HughE
+1  A: 

To avoid using other packages or define new classes, you can use datetime.timedelta with time.altzone, which should work if a daylight saving timezone is used

import datetime, time
dt_utc = datetime.datetime.utcnow()

# convert UTC to local time
dt_local = dt_utc - datetime.timedelta(seconds=time.altzone)

print str(dt_local)

Here we make use of the fact that time.altzone contains the local offset in seconds with UTC. There may be some rough edges in the Python source regarding the time library and altzone though.

catchmeifyoutry