The best I can come up with for now is this monstrosity:
>>> datetime.utcnow() \ ... .replace(tzinfo=pytz.UTC) \ ... .astimezone(pytz.timezone('Australia/Melbourne')) \ ... .replace(hour=0,minute=0,second=0,microsecond=0) \ ... .astimezone(pytz.UTC) \ ... .replace(tzinfo=None) datetime.datetime(2008, 12, 16, 13, 0)
I.e., in English, get the current time (in UTC), convert it to some other timezone, set the time to midnight, then convert back to UTC.
I’m not just using now() or localtime() as that would use the server’s timezone, not the user’s timezone.
I can’t help feeling I’m missing something, any ideas?
I think you can shave off a few method calls if you do it like this:
BUT… there is a bigger problem than aesthetics in your code: it will give the wrong result on the day of the switch to or from Daylight Saving Time.
The reason for this is that neither the datetime constructors nor
replace()take DST changes into account.For example:
However, the documentation for
tz.localize()states:Thus, your problem is solved like so:
No guarantees for dates before 1582, though.