same code,different answers on windows and ubuntu [duplicate] - python

I have the following code:
import datetime
dt = 1546955400
print(datetime.datetime.fromtimestamp(dt))
When I run this code on my local machine, I get the correct (expected) time which is
2019-01-08 15:50:00.
However I tried running this exact same code on a VM and the result was
2019-01-08 13:50:00 (two hours earlier). Why is this is happening and how can I fix it so that I always get the first one regardless of where the code is running?

datetime.datetime.fromtimestamp() returns local time. From the documentation:
Return the local date and time corresponding to the POSIX timestamp, such as is returned by time.time(). If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive.
The timestamp value is an offset in seconds from the UNIX epoch value, midnight 1 January 1970, in the UTC timezone. The local time is a system-wide configured offset from UTC, the local timezone.
If your VM is producing unexpected results, you need to configure the timezone of the OS.
Alternatively, ignore timezones and only deal with time in the UTC timezone. For timestamps, that means using the datetime.datetime.utcfromtimestamp() function.
Your specific timestamp is 13:50 UTC:
>>> dt = 1546955400
>>> from datetime import datetime
>>> datetime.utcfromtimestamp(dt)
datetime.datetime(2019, 1, 8, 13, 50)
>>> print(_)
2019-01-08 13:50:00
so your VM is either set to the UTC or the GMT timezone (the latter is currently at UTC+0, until the switch to the UK daylight saving timezone BST). Your local system is in a UTC+2 timezone, given your stated location from your profile that'd be EEE, Easter European Time.
Another option is to create a timezone-aware timestamp by passing in a tz argument. If you have a specific UTC offset, just create a datetime.timezone() instance for that offset:
utcplus2 = datetime.timezone(datetime.timedelta(hours=2))
datetime.datetime.fromtimestamp(dt, utcplus2)
However, it is usually better to store and operate on UTC datetime instances everywhere, and only convert to specific timezones when displaying information to users. This simplifies datetime handling as it lets you avoid a number of timezone corner cases and problems, such as mixing datetime information from different timezones and timezones with a summer and winter time distinction.

Related

Unix to Timezone Conversion, Offset element

I converted a UNIX timestamp to a human format (sorry I do not know the exact name of it) in a specific timezone (Africa/Algeria) and it evaluated to this: 2020-06-05 19:45:21+01:00. I looked into the datetime module documentation and from what I understood the +01:00, it is the +/-HH:MM offset from the UTC.
What I do not understand is why it is returned with the datetime object given it is already converted to the indicated timezone?
Could someone explain it to me?
Thanks.
POSIX timestamps (Unix time) represent time in seconds since the epoch, 1970-01-01 UTC. No time zone issues involved here. datetime objects on the other hand can be naive (not contain any time zone information) or time zone aware. What you have is a time zone aware datetime object - its string representation prints out as "2020-06-05 19:45:21+01:00". If it had been naive, it would only print "2020-06-05 19:45:21". The repr should also show you a specific time zone, e.g.
print(repr(dt_obj))
>>> datetime.datetime(2020, 6, 5, 19, 45, 21, tzinfo=tzfile('Africa/Algiers'))
The important point is that 2020-06-05 19:45:21+01:00 can be converted back to POSIX timestamp without ambiguity:
from datetime import datetime
datetime.fromisoformat("2020-06-05 19:45:21+01:00").timestamp()
# 1591382721.0
If it wasn't for the +01:00 (no tzinfo), Python would assume that the datetime object belongs in local time, i.e. OS setting; meaning that machines in different time zones would get a different timestamp. I'm on UTC+2, so I would get:
datetime.fromisoformat("2020-06-05 19:45:21").timestamp()
# 1591379121.0
which gives the same timestamp as
datetime.fromisoformat("2020-06-05 19:45:21+02:00").timestamp()
# 1591379121.0
The difference is that with the "+02:00" (tzinfo defined), it is obvious what is happening.

python: utcfromtimestamp vs fromtimestamp, when the timestamp is based on utcnow()

Pretty sure it's an easy one but I don't get it.
My local TZ is currently GMT+3, and when I take timestamp from datetime.utcnow().timestamp() it is indeed giving me 3 hours less than datetime.now().timestamp()
During another process in my flow, I take that utc timestamp and need to turn it into datetime.
When I'm doing fromtimestamp I get the right utc hour, but when I'm using utcfromtimestamp I get another 3 hours offset.
The documentation, though, asks me to use fromtimestamp for local timezone, and utcfromtimestamp for utc usages.
What am I missing ? is the initial assumption for both funcs is that the timestamp is given in local timezone ?
Thank you :)
The key thing to notice when working with datetime objects and their POSIX timestamps (Unix time) at the same time is that naive datetime objects (the ones without time zone information) are assumed by Python to refer to local time (OS setting). In contrast, a POSIX timestamp (should) always refer to seconds since the epoch UTC. You can unambiguously obtain that e.g. from time.time(). In your example, not-so-obvious things happen:
datetime.now().timestamp() - now() gives you a naive datetime object that resembles local time. If you call for the timestamp(), Python converts the datetime to UTC and calculates the timestamp for that.
datetime.utcnow().timestamp() - utcnow() gives you a naive datetime object that resembles UTC. However, if you call timestamp(), Python assumes (since naive) that the datetime is local time - and converts to UTC again before calculating the timestamp! The resulting timestamp is therefore off from UTC by twice your local time's UTC offset.
A code example. Let's make some timestamps. Note that I'm on UTC+2 (CEST), so offset is -7200 s.
import time
from datetime import datetime, timezone
ts_ref = time.time() # reference POSIX timestamp
ts_utcnow = datetime.utcnow().timestamp() # dt obj UTC but naive - so also assumed local
ts_now = datetime.now().timestamp() # dt obj naive, assumed local
ts_loc_utc = datetime.now(tz=timezone.utc).timestamp() # dt obj localized to UTC
print(int(ts_utcnow - ts_ref))
# -7200 # -> ts_utcnow doesn't refer to UTC!
print(int(ts_now - ts_ref))
# 0 # -> correct
print(int(ts_loc_utc - ts_ref))
# 0 # -> correct
I hope this clarifies that if you call datetime.utcfromtimestamp(ts_utcnow), you get double the local time's UTC offset. Python assumes (which I think is pretty sane) that the timestamp refers to UTC - which in fact, it does not.
My suggestion would be to use timezone-aware datetime objects; like datetime.now(tz=timezone.utc). If you're working with time zones, the dateutil library or Python 3.9's zoneinfo module are very helpful. And if you want to dig deep, have a look at the datetime src code.

Python: How to convert unixtimestamp and timezone into datetime object?

I have a csv file with the datetime in unixtimestamp format with milliseconds and timezone information in milliseconds as well. I want to convert this into a more usable datetime format for further processing.
For example, the time is 1437323953822 and timezone is -14400000.
I can convert the timestamp into a datetime by using
datetime.datetime.fromtimestamp(1437323953822/1000)
But how do I now incorporate the timezone which is -4 UTC time from what I know.
(-14400000 / 1000 / 60 / 60) = -4
How do I use this timezone to get the actual time?
fromtimestamp can also take another parameter for the timezone, a subclass of tzinfo:
classmethod datetime.fromtimestamp(timestamp[, tz])
Return the local date and time corresponding to the POSIX timestamp,
such as is returned by time.time(). If optional argument tz is
None or not specified, the timestamp is converted to the platform’s
local date and time, and the returned datetime object is naive.
Else tz must be an instance of a class tzinfo subclass, and the
timestamp is converted to tz‘s time zone. In this case the result is
equivalent to
tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz)).
fromtimestamp() already returns your local time i.e., you don't need to attach the utc offset if fromtimestamp() determines it correctly automatically:
#!/usr/bin/env python
from datetime import datetime
local_time = datetime.fromtimestamp(1437323953822 * 1e-3)
# -> datetime.datetime(2015, 7, 19, 12, 39, 13, 822000)
fromtimestamp() may fail in some cases e.g., if the local timezone had a different utc offset in the past and fromtimestamp() does not use a historical timezone database on a given platform (notably, Windows). In that case, construct the local time explicitly from utc time and the given utc offset:
#!/usr/bin/env python
from datetime import datetime, timedelta
utc_time = datetime(1970, 1, 1) + timedelta(milliseconds=1437323953822)
utc_offset = timedelta(milliseconds=-14400000)
local_time = utc_time + utc_offset
# -> datetime.datetime(2015, 7, 19, 12, 39, 13, 822000)
Python always expects POSIX Epoch and therefore it is ok to hardcode it. The explicit formula may be more precise (no rounding error) and it may accept a wider range of input timestamps (fromtimestamp() range depends on platform and may be narrower than the corresponding datetime range).
This question is old but I want to give a slightly more comprehensive answer.
About the unix timestamp:
The timestamp is the number of seconds (or milliseconds) elapsed since an absolute point in time, midnight of Jan 1 1970 in UTC time. (UTC is Greenwich Mean Time without Daylight Savings time adjustments.)
fromtimestamp does convert the unix timestamp to your platform's time. If you are working across different platforms, it is important to set the platform's timezone correctly. If you want it to be in UTC instead, then utcfromtimestamp should be used instead.
To answer OP's question directly, the following code will create a timezone based on the offset.
from datetime import datetime, timezone, timedelta
ts = int('1604750712')
tz = timezone(-timedelta(hours=4))
print(datetime.fromtimestamp(ts, tz).strftime('%Y-%m-%d %H:%M:%S'))
timezone object is an concrete class of tzinfo, I have initiated it with a negative offset of 4 hours from UTC.
from datetime import datetime
import pytz # pip install pytz
tz = pytz.timezone('Asia/Dubai')
ts = int('1604750712')
print(datetime.fromtimestamp(ts,tz).strftime('%d-%m-%Y %H:%M:%S'))

Python - convert naive datetime to UTC

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)
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([])

Getting the correct timezone offset in Python using local timezone

Ok let me first start by saying my timezone is CET/CEST. The exact moment it changes from CEST to CET (back from DST, which is GMT+2, to normal, which GMT+1, thus) is always the last Sunday of October at 3AM. In 2010 this was 31 October 3AM.
Now note the following:
>>> import datetime
>>> import pytz.reference
>>> local_tnz = pytz.reference.LocalTimezone()
>>> local_tnz.utcoffset(datetime.datetime(2010, 10, 31, 2, 12, 30))
datetime.timedelta(0, 3600)
This is wrong as explained above.
>>> local_tnz.utcoffset(datetime.datetime(2010, 10, 30, 2, 12, 30))
datetime.timedelta(0, 7200)
>>> local_tnz.utcoffset(datetime.datetime(2010, 10, 31, 2, 12, 30))
datetime.timedelta(0, 7200)
Now it is suddenly correct :/
I know there are several questions about this already, but the solution given is always "use localize", but my problem here is that the LocalTimezone does not provide that method.
In fact, I have several timestamps in milliseconds of which I need the utcoffset of the local timezone (not just mine, but of anyone using the program). One of these is 1288483950000 or Sun Oct 31 2010 02:12:30 GMT+0200 (CEST) in my timezone.
Currently I do the following to get the datetime object:
datetime.datetime.fromtimestamp(int(int(millis)/1E3))
and this to get the utcoffset in minutes:
-int(local_tnz.utcoffset(date).total_seconds()/60)
which, unfortunately, is wrong in many occasions :(.
Any ideas?
Note: I'm using python3.2.4, not that it should matter in this case.
EDIT:
Found the solution thanks to #JamesHolderness:
def datetimeFromMillis(millis):
return pytz.utc.localize(datetime.datetime.utcfromtimestamp(int(int(millis)/1E3)))
def getTimezoneOffset(date):
return -int(date.astimezone(local_tz).utcoffset().total_seconds()/60)
With local_tz equal to tzlocal.get_localzone() from the tzlocal module.
According to Wikipedia, the transition to and from Summer Time occurs at 01:00 UTC.
At 00:12 UTC you are still in Central European Summer Time (i.e. UTC+02:00), so the local time is 02:12.
At 01:12 UTC you are back in the standard Central European Time (i.e. UTC+01:00), so the local time is again 02:12.
When changing from Summer Time back to standard time, the local time goes from 02:59 back to 02:00 and the hour repeats itself. So when asking for the UTC offset of 02:12 (local time), the answer could truthfully be either +01:00 or +02:00 - it depends which version of 02:12 you are talking about.
On further investigation of the pytz library, I think your problem may be that you shouldn't be using the pytz.reference implementation, which may not deal with these ambiguities very well. Quoting from the comments in the source code:
Reference tzinfo implementations from the Python docs.
Used for testing against as they are only correct for the years
1987 to 2006. Do not use these for real code.
Working with ambiguous times in pytz
What you should be doing is constructing a timezone object for the appropriate timezone:
import pytz
cet = pytz.timezone('CET')
Then you can use the utcoffset method to calculate the UTC offset of a date/time in that timezone.
dt = datetime.datetime(2010, 10, 31, 2, 12, 30)
offset = cet.utcoffset(dt)
Note, that the above example will throw an AmbiguousTimeError exception, because it can't tell which of the two versions of 02:12:30 you meant. Fortunately pytz will let you specify whether you want the dst version or the standard version by setting the is_dst parameter. For example:
offset = cet.utcoffset(dt, is_dst = True)
Note that it doesn't harm to set this parameter on all calls to utcoffset, even if the time wouldn't be ambiguous. According to the documentation, it is only used during DST transition ambiguous periods to resolve that ambiguity.
How to deal with timestamps
As for dealing with timestamps, it's best you store them as UTC values for as long as possible, otherwise you potentially end up throwing away valuable information. So first convert to a UTC datetime with the datetime.utcfromtimestamp method.
dt = datetime.datetime.utcfromtimestamp(1288483950)
Then use pytz to localize the time as UTC, so the timezone is attached to the datetime object.
dt = pytz.utc.localize(dt)
Finally you can convert that UTC datetime into your local timezone, and obtain the timezone offset like this:
offset = dt.astimezone(cet).utcoffset()
Note that this set of calculations will produce the correct offsets for both 1288483950 and 1288487550, even though both timestamps are represented by 02:12:30 in the CET timezone.
Determining the local timezone
If you need to use the local timezone of your computer rather than a fixed timezone, you can't do that from pytz directly. You also can't just construct a pytz.timezone object using the timezone name from time.tzname, because the names won't always be recognised by pytz.
The solution is to use the tzlocal module - its sole purpose is to provide this missing functionality in pytz. You use it like this:
import tzlocal
local_tz = tzlocal.get_localzone()
The get_localzone() function returns a pytz.timezone object, so you should be able to use that value in all the places I've used the cet variable in the examples above.
Given a timestamp in milliseconds you can get the utc offset for the local timezone using only stdlib:
#!/usr/bin/env python
from datetime import datetime
millis = 1288483950000
ts = millis * 1e-3
# local time == (utc time + utc offset)
utc_offset = datetime.fromtimestamp(ts) - datetime.utcfromtimestamp(ts)
If we ignore time around leap seconds then there is no ambiguity or non-existent times.
It supports DST and changes of the utc offset for other reasons if OS maintains a historical timezone db e.g., it should work on Ubuntu for any past/present date but might break on Windows for past dates that used different utc offset.
Here's the same using tzlocal module that should work on *nix and Win32 systems:
#!/usr/bin/env python
from datetime import datetime
from tzlocal import get_localzone # pip install tzlocal
millis = 1288483950000
ts = millis * 1e-3
local_dt = datetime.fromtimestamp(ts, get_localzone())
utc_offset = local_dt.utcoffset()
See How to convert a python utc datetime to a local datetime using only python standard library?
To get the utc offset in minutes (Python 3.2+):
from datetime import timedelta
minutes = utc_offset / timedelta(minutes=1)
Don't use pytz.reference.LocalTimezone(), it is only for tests.
import pytz, datetime
tz = timezone('CET')
tz.utcoffset(datetime.datetime.now()).total_seconds()
7200.0

Categories