Python pytz: convert local time to utc. Localization does not translate

I have a database that stores datetime as UTC. I need to look at information from a certain time, but the date and time are given in local time, say, "Europe / Copenhagen." I have been given the following:

year = 2012; month = 12; day = 2; hour = 13; min = 1; 

So, I need to convert them to UTC so that I can find them in the database. I want to do this with pytz . I look localize :

  local_tz = timezone('Europe/Copenhagen') t = local_tz.localize(datetime.datetime(year, month, day, hour, min)) 

But I'm confused about localize() . Is it assumed that year, etc. Provided to me by local time? Or, are they supposed to be given in UTC, and now he has converted them to local time?

print t gives me:

 2012-12-02 13:01:00+01:00 

So it seems that he suggested that the original year, etc. was in utc; hours now 13 + 1 instead of 13. So what should I do instead? I read the pytz documentation and it does not make me more clear to me. It says a lot that everything is complicated, so I'm not sure if pytz really solves these problems. And I don’t always know if examples show what things work or what won’t work.

I tried to normalize:

 print local_tz.normalize(t) 

This gives me the same result as print t.

EDIT: with the figures above for the year, etc. It must match the information in the database on 2012-12-2 12:01. (since Copenhagen is utc + 1 on this date)

+8
python timezone pytz
source share
2 answers

localize() binds the time zone to a naive instance of datetime.datetime in the local time zone.

If you have datetime values ​​in your local time zone, localize in that time zone, then use .astimezone() to specify the value in UTC:

 >>> localdt = local_tz.localize(datetime.datetime(year, month, day, hour, min)) >>> localdt.astimezone(pytz.UTC) datetime.datetime(2012, 12, 2, 12, 1, tzinfo=<UTC>) 

Note that you do not need to do this; datetime objects with a time zone can be compared; they will both be normalized to UTC for the test:

 >>> localdt.astimezone(pytz.UTC) == localdt True 
+16
source share

If you know that the inbound time view is in the Europe/Copenhagen time zone, you can create it as a time zone to start with:

 local_tz = timezone('Europe/Copenhagen') t = local_tz.localize(datetime.datetime(year, month, day, hour, min)) 

Then you can "convert" this to UTC with:

 t_utc = t.astimezone(pytz.UTC) 

but this may not be necessary, depending on how reasonable your database drivers are. t and t_utc represent the same point in time, and the code of good behavior should relate to them interchangeably. A tuple (year, month, day, hour, minute, second, …) is just a human-readable representation of this moment in a specific time zone and calendar system.

0
source share

All Articles