views:

1061

answers:

3

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?

A: 

Setting the TZ environment variable modifies what timezone Python's date and time functions work with.

>>> time.gmtime()
(2008, 12, 17, 1, 16, 46, 2, 352, 0)
>>> time.localtime()
(2008, 12, 16, 20, 16, 47, 1, 351, 0)
>>> os.environ['TZ']='Australia/Melbourne'
>>> time.localtime()
(2008, 12, 17, 12, 16, 53, 2, 352, 1)
Ignacio Vazquez-Abrams
Aside from not wanting to use the TZ variable to control this, that doesn't actually tell me how to find midnight, just the current time.
Tom
+1  A: 

Each time zone has a number, eg US/Central = -6. This is defined as the offset in hours from UTC. Since 0000 is midnight, you can simply use this offset to find the time in any time zone when it is midnight UTC. To access that, I believe you can use

 time.timezone

According to The Python Docs, time.timezone actually gives the negative value of this number:

time.timezone

The offset of the local (non-DST) timezone, in seconds west of UTC (negative in most of Western Europe, positive in the US, zero in the UK).

So you would simply use that number for the time in hours if it's positive (i.e., if it's midnight in Chicago (which has a +6 timezone value), then it's 6000 = 6am UTC).

If the number is negative, subtract from 24. For example, Berlin would give -1, so 24 - 1 => 2300 = 11pm.

Colin
I think you're on the right track, but how do you know what date to start with? i.e. a few hours ago, it was the 17th here in Melbourne, while it was still the 16th in UTC.
Tom
The question is about local Midnight. The day relationship is fixed by the UTC offset for the timezone -- at local midnight.
S.Lott
adding/substracting tz differences by hand might have issues around the switch from and to DST
hop
If it's the number of SECONDS west, you wouldn't want to subtract it from 24...
R. Bemrose
+2  A: 

I think you can shave off a few method calls if you do it like this:

>>> from datetime import datetime
>>> datetime.now(pytz.timezone("Australia/Melbourne")) \
            .replace(hour=0, minute=0, second=0) \
            .astimezone(pytz.utc)
hop
Thanks, that's definitely neater and a little more self-descriptive.
Tom
don't forget millisecond
joeforker