delorean
docs show this way to get the current time in a given timezone using datetime
:
from datetime import datetime
from pytz import timezone
EST = "US/Eastern"
UTC = "UTC"
d = datetime.utcnow()
utc = timezone(UTC)
est = timezone(EST)
d = utc.localize(d)
d = est.normalize(EST)
and compare it with the delorian-based code:
from delorean import Delorean
EST = "US/Eastern"
d = Delorean(timezone=EST)
I believe the datetime
example should be written as:
from datetime import datetime
import pytz
eastern_timezone = pytz.timezone("US/Eastern")
d = datetime.now(eastern_timezone)
that is more concise.
Are there any cases when the last code example fails while the first one continues to work?
Update: the current example:
from datetime import datetime
import pytz
d = datetime.utcnow()
d = pytz.utc.localize(d)
est = pytz.timezone('US/Eastern')
d = est.normalize(d)
return d
that is still too verbose.
The question stills stands: do you need the explicit round-trip via utc and tz.normalize()
or can you use datetime.now(tz)
instead?
As far as I can tell, there are no scenarios where it could fail.
datetime.now
invokes thefromutc
function on thetzinfo
instance passed in the parameter. All conversions from UTC to local time are unambiguous, so there are no opportunities for failure.Also, the original code does not even work.
This would appear to pass a string as the only parameter to
normalize
, which is intended to take adatetime
. This gives:I believe they meant to write:
That said, I don't think the verbosity of their code adds much value. As you noted, it's just as easy to do this in a single step:
Looking at the cpython source code for
datetime.now
, I can see that when atzinfo
object is provided, it calls thefromutc
method on that object.Then, in the pytz source, I see that the
fromutc
method is implemented differently depending on whether the zone ispytz.UTC
, or an instance ofStaticTzInfo
, orDstTzInfo
. In all three cases, the transformation from the input UTC value to the target time zone is unambiguous. Here is theDstTzInfo
implementation, which is the more complex of the three:This would appear to find the transition from
_utc_transition_times
of the time zone, then apply it to the returneddatetime
. There are no ambiguities in this direction, so the results will be equivalent.Also worth noting, in the
datetime
docs it says thatdatetime.now
is equivalent to calling:Given the source of
fromutc
in pytz I showed earlier, I'm not sure that this is any different than just:But in either case, I don't think
localize
andnormalize
are necessary.