Created
March 6, 2011 22:23
-
-
Save simonw/857786 to your computer and use it in GitHub Desktop.
Convert a local datetime object to a UTC string represestation, taking daylight savings time in to account
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| Convert a local datetime object to a UTC string represestation, taking | |
| daylight savings time in to account. Here's an example - the clocks change | |
| at 2am on March 13th 2011. | |
| >>> to_utc_datestring(datetime.datetime(2011, 3, 11, 17, 30)) | |
| '20110311T233000Z' | |
| >>> to_utc_datestring(datetime.datetime(2011, 3, 15, 17, 30)) | |
| '20110315T223000Z' | |
| You can use http://www.timezoneconverter.com/cgi-bin/tzc.tzc to check results | |
| """ | |
| import pytz # http://pytz.sourceforge.net/ | |
| def to_utc_datestring(localtime, timezone='America/Chicago'): | |
| tz = pytz.timezone(timezone) | |
| return (localtime.replace( | |
| tzinfo = tz | |
| ).astimezone( | |
| pytz.utc | |
| ) - tz.dst(localtime)).strftime( | |
| '%Y%m%dT%H%M%SZ' | |
| ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment