3

I have date that I get in specific timezone time, but system deals with it as UTC and later it converts it back in that timezone, messing time.

For example like this:

I get this time: 2014-05-05 10:50:30. its datetime object. It has no timezone info, but I can get timezone info from user that uses that time. The thing is this time is showed as 'Europe/Vilnius' time, but system deals with it as UTC and when it outputs time to user it adds +3 hours showing wrong time. It does not matter if I change timezone to users timezone on that datetime object, it still outputs with +3 hours.

For example (snippet of code):

from datetime import datetime
import pytz         
create_date = datetime.strptime(stage_log.create_date, "%Y-%m-%d %H:%M:%S")
tz = pytz.timezone(self.user_id.tz)
create_date = create_date.replace(tzinfo=pytz.utc)

This does not do anything and I still get wrong time.

Is there a way to move time to be correct UTC time(so then system correctly convert to users timezone) like this:

2014-05-05 10:50:30 -> convert to UTC. If timezone is 'Europe/Vilnius', it should convert that time to 2014-05-05 07:50:30. Then when system automatically does conversions it would correctly display 2014-05-05 10:50:30, because thats the time it should display.

Also if there is a way to just get number of hours that given timezone differs from UTC, then I could just do as simple as that:

create_date.replace(hour=create_date.hour-timezone_difference)

Andrius
  • 19,658
  • 37
  • 143
  • 243
  • This one saved the day - http://stackoverflow.com/questions/79797/how-do-i-convert-local-time-to-utc-in-python – Andrius Aug 09 '14 at 12:28

1 Answers1

1

While this question does not specifically reference odoo, hopefully the following may help others:

Odoo - convert datetime to UTC: (note: in this example self.start_date is a fields.Date)

start_date = fields.Datetime.to_string(pytz.timezone(self.env.context['tz']).localize(fields.Datetime.from_string(self.start_date), is_dst=None).astimezone(pytz.utc))

similar but with +24 hrs

end_date = fields.Datetime.to_string(pytz.timezone(self.env.context['tz']).localize(fields.Datetime.from_string(self.end_date), is_dst=None).astimezone(pytz.utc) + timedelta(hours=24))

This was used because the passed values (self.start_date) were field.Date and therefor did not get affected by timezones, while the target stored fields were fields.Datetime and therefor stored in UTC.

start_date/end_date which are now in UTC can then be used in a self.env[''].search([])

Palza
  • 642
  • 5
  • 12