140 points · by tomerbd · 4y ago · 103 comments
Sure, you can format datetimes in localised formats for end users, but standardising on UTC+0 and RFC-3339 for programming and maintenance purposes just prevents so much confusion and hassle.
Not that I've ever had to spend a day trying to troubleshoot a bug that was alerted by our monitoring system at 2020-11-09T09:11:05Z (as it was defaulting to UTC), but the relevant logs were timestamped at 10:11:05 09/11/2020 (I only wished they'd used the normal German period separators in the date to give me a clue) because of course your German colleagues want their timestamps in German format and defaulting to CET...
When you have colleagues in Europe, Oceania, and distributed from coast to coast in the US, doing everything in UTC means everyone only has to do one mental conversion from their local timezone to UTC, as opposed to trying to remember if they're in LA or New York, or if they're in Mountain Time, if they're in the parts of the US that are Mountain Time but don't do daylight savings.
It gets even more fun when such events happen during the switch between daylight saving time (like CEST) and standard time (like CET).
Ah, daylight savings.
(I always set CW back to UTC, for consistency)
I also remember that AWS used to display some datetimes in Pacific Standard Time, which is completely useless to somebody outside the US, however I haven't seen that in a while anymore.
Similar to the global language switch I wish the AWS Management Console would allow setting in which timezone to display datetimes globally as well.
"2020-11-09T09:11:05Z" uniquely identifies a point in time. "10:11:05 09/11/2020" is some time 11 minutes past the hour on either September 11th or November 9th. It doesn't identify anything.
Edit: Or 41 minutes past the hour.
I don't want my equality operator doing timezone conversions. If one type has no timezone attached and one does, then you probably shouldn't be able to compare them at all. Likewise, for a type that has a timezone attached, if the timezone differs between a and b, then I want a == b to return false, even if it represents the same instant in time.
Equality can be a tricky thing. Named functions are the way to go when two different developers might intuit different behaviors.
I work on the Python API of a timeseries database and it’s very frustrating to have to accept timestamp objects without time zone because you don’t know what to do with them. People aren’t aware of this constraint, which leads to unexpected behavior.
Only time differences do not have a timezone.
When Python continues to use the word "timestamp" for a time value with an unknown time zone, then that is the fault of Python, because the name is completely inappropriate.
I assume that whoever enabled a value "None" to be possible for the timezone did not really expect that anyone will ever use a timestamp with unknown timezone, but that in such cases there is a timezone known to the programmer, which is not stored with the timestamps, and that it is the responsibility of the programmer to restore the timezone whenever necessary.
As of now, we just reject any timestamp without an explicit timezone and try to explain to our users why utcnow() is bad. People are generally very surprised that this issue exists at all.
> ts = 1571595618.0
This a timestamp, there is no TZ data required.
> x = datetime.utcfromtimestamp(ts)
Now for some reason the developer cares about UTC all of a sudden?
If the developer doesn't care about the TZ, they should use:
datetime.fromtimestamp(ts)
The main issue is that .utcfromtimestamp and .fromtimestamp both return naive datetimes, instead of aware ones with the timezone property set to UTC or the local timezone respectively.
Nobody argues for that. Especially since we’re comparing timestamps (floats), not datetimes (objects). Let’s go line by line :
> ts = 1571595618.0
This is 2019-10-20 18:20:18.000 UTC
> x = datetime.utcfromtimestamp(ts)
I would therefore expect x to be 2019-10-20 18:20:18.000 UTC
> x_ts = x.timestamp()
I would therefore expect x_ts to be 1571595618.0. Which is surprisingly not.
Nowhere the equality operator was involved in the surprise.
I have, however, been using python so long that I’ve gotten used to the way things sort-of-work and developed such a healthy caution around it’s unintuitive built-in time zone handling.
>>> from datetime import datetime
>>> ts = 1571595618.0
>>> x = datetime.utcfromtimestamp(ts)
>>> x_ts = x.timestamp()
>>> type(x_ts)
<class 'float'>
>>> type(x)
<class 'datetime.datetime'>Really? So if you want to compare that two times are really the same time for two different timezones, you'd want to convert them to UTC first? What's the use case for this?
Seems like the less-used way to me.
No, most people do want to compare times in different TZs without the extra cruft.
Unfortunately, now that the default has been introduced, there seems no way to get to get out of this situation while preserving backwards-compatibility. The lesson here, perhaps, is to not make it easier to use that which should have been deprecated.
Thanks for your clear and to-the-point article!
This is why for anything that uses timezone, I use pendulum: https://pendulum.eustace.io/
It's compatible with the datetime api, but it has sane default, nice tools to convert between timezone, some cool date adjustment stuff, and can humanize time in several languages.
Basically, datetime has the same problem as text vs raw bytes in python 2.7, except it has never been fixed.
On Java, you can use the forbidden-apis build plugin (https://github.com/policeman-tools/forbidden-apis) to fail the build whenever a timezone or locale or charset is not specified explicitly (it forbids the methods from the Java API which use an implicit timezone/locale/charset). I don't know whether there's something similar for Python; it might be harder because Python is much more dynamic (though it might be possible to use monkeypatching to warn whenever the bad methods are used).
If only it returned something that contained the UTC offset in which is was created, then all of this would be much easier to deal with. Conversions to timestamps would just work, and comparisons would just work.
Note that I said "UTC offset", not "timezone". datetime doesn't deal in UTC offsets, it deals in timezones. And timezones are a zillion times more complicated, which is why no one want to deal with them on the critical path, and no one has ever proposed having now() return an object with .tzinfo set. Logical though it may be.
I'm not bashing anyone that's involved as I realize we're all human and prone to mistakes, I just wish we could all do better.
I should mention that the warnings are relatively recent, added in 3.8.
https://docs.python.org/3/library/datetime.html#datetime.dat...
I suspect that the author of Jodatime (which effectively became the java.time API), who was notorious for being almost Linus Torvalds like in his attitudes and approaches, was probably once a very nice and kind individual. Until he started implementing a datetime library.
I mean, he nailed it, but at what cost? java.time.* is my second favourite datetime API, the first being Postgres'.
I'm actually surprised the source code of Jodatime isn't entirely in Zalgotext, technically it'd be valid Java code (I'm pretty sure, anyway).
It's surprising how poorly the situation with timezones is understood in the industry.
We have courses about compilers, databases, data structures, algorithms, cryptography. It's surprising we don't have courses about dates and time.
https://docs.python.org/3/library/datetime.html#datetime.dat...
"If self is naive, it is presumed to represent time in the system timezone."
presumed is kind of a bad word in Python. I would never write an API today that "presumed" something that can be lots of other things and I would not allow any tz conversion on a naive datetime without requiring the existing known timezone be passed.
not following why the "this is the system timezone" must be hardcoded to be an invisible assumption, as opposed to something somewhat explicit. I mean this is literally not far off from a simple namechange of ".astimezone()".
A follow up from April 2022: https://blog.ganssle.io/articles/2022/04/naive-local-datetim...
Inconsistent through various python version, poorly documented and utterly confusing to use, as demonstrated by this article.
It's not hard to come up with an improved library design. But it is extremely hard to improve it while remaining compatible with the billions of lines of Python code out there.
I use the stdlib datetime.datetime with pytz, with a few in-house helper functions, and it's frankly kinda awful across the board but we deal with it.
Pendulum is really nice, and I want to use it as my daily driver, but I unfortunately found some timezone bugs [1] in v2 that make me hesitant to trust it for what we are doing in production (it screws up DST when doing `.utcoffset()`). If you aren't constantly dealing with data timezones from all over the world, it's probably fine, and it's the only one that the least surprising thing at each step.
Pytz has the whole .localize footgun.
The std datetime lib has horrible ergonomics and can't even cope with IANA timezones until the zoneinfo module was introduced in 3.9. Every single day it bugs me that the classes `datetime` and `time` are lowercase, and there is no consensus on datetime.datetime vs from datetime import datetime.
I tried using arrow and while I applaud them for moving away from the horrible datetime class, that makes it pretty much incompatible with any other time library, including things like pydantic and orjson.
I don't have much experience with dateutil.
1 - https://github.com/sdispater/pendulum/issues/655
Seems to have started in 2.x but is fixed in the 3.0alpha. You have to be specifically using utcoffset, which in general is probably not something you should do and use the timezone types to do conversions, but it was enough to give me pause
Mostly I'm not operating at the application / presentation layers.
This does cause friction when taking things at "interface value" (Sherry Turckle): just like everybody (I'm sure) I `grep -E '^2022-10-09'` or `grep -E '^Oct 09'` (looking at YOU, journalctl!). But I can also `perl -ne 'BEGIN { use Time::Local; $TIME = timelocal(0,0,5,7,8,122); } $t = (split /\s+/)[0]; $t > $TIME && $t < ($TIME + 60) && print;'`.
I have a little python script which does pretty much the same thing, with some attempts to recognize and fill in for rando date patterns just to make it a bit more universal.
I would counsel against storing human readable dates in databases and use unix time.
Arrow makes the unfortunate conflation of Date, Time, and Datetime types, which causes all sorts of subtle errors when working with Dates that don't have times attached, and vice versa.
The best Datetime lib I've seen in any language is Chrono in Rust. Maybe there's a way to port it to Python via FFI.
For python the important thing to understand is the difference between tz aware and naive datetime objects. But after you can do depending on your needs.
For example, if you ensure to convert your inputs to UTC and output UTC also, you can easily just work with utcnow by only dealing with UTC internally.
You would have to do that to store datetime in MySQL for example.
Imagine you have a software which deals with CSV files sent by clients. Clients are international corporations. What's the timezone the datetimes in the CSV files belongs to?
# what I used to do:
>>> datetime.utcnow().replace(tzinfo=timezone.utc)
# what I'll be doing from now on:
>>> datetime.now(timezone.utc)And just the naive/aware crap is almost like the unicode conversion previously. Ugh