2

I am trying the following:

import datetime
from pytz import timezone

date = datetime.datetime(2011,01,01) # this is in UTC time
tz = timezone('US/Pacific')

How would I then convert this datetime into the US/Pacific equivalent?

gypaetus
  • 6,873
  • 3
  • 35
  • 45
David542
  • 104,438
  • 178
  • 489
  • 842

2 Answers2

1

Its been asked before, but any way you can find it here -

http://www.saltycrane.com/blog/2009/05/converting-time-zones-datetime-objects-python/

If you know the hour difference to which you would like to change you can do following -

e.g. - your timezone is +2 hours to UTC

from datetime import datetime, timedelta

current_utc = datetime.utcnow()
my_timezone = current_utc + timedelta(hours=2)
Mutant
  • 3,663
  • 4
  • 33
  • 53
  • the input is *local time*, not UTC time. If you know utc offset for the given local time then to convert local time to utc: `utc_time = local_time - utc_offset` – jfs Oct 04 '14 at 10:09
-1

You can provide the tzinfo argument to the datetime function:

tz = timezone('US/Pacific')
date = datetime.datetime(2011, 01, 01, tzinfo=tz)

Or convert an existing datetime object to another timezone:

date_pacific = date.astimezone(timezone('US/Pacific'))
gypaetus
  • 6,873
  • 3
  • 35
  • 45
  • -1: it is incorrect. Don't pass pytz timezone to `datetime()` constructor if the timezone has multiple UTC offsets (same place, different time). [Use `tz.localize()` instead](http://stackoverflow.com/a/26190657/4279). – jfs Oct 04 '14 at 10:07
  • like in US/Pacific timezone – gypaetus Oct 05 '14 at 02:37