开发者

Python/Django: Have DB TimeZoneField for user, how do I use that with datetime and time to get strftime() like '%Y-%m-%dT%H:%M:%S.000Z'?

开发者 https://www.devze.com 2023-01-22 23:21 出处:网络
I have a DB \"TimeZoneField\" type for users, how do I use that with the \"datetime.datetime()\" ob开发者_如何学JAVAject to get a strftime() string like \'%Y-%m-%dT%H:%M:%S.000Z\'?This was for Google

I have a DB "TimeZoneField" type for users, how do I use that with the "datetime.datetime()" ob开发者_如何学JAVAject to get a strftime() string like '%Y-%m-%dT%H:%M:%S.000Z'?


This was for Google Calendar's Python data API feed and it was a lot of work because Python's datetime library doesn't support ISO 8601: http://wiki.python.org/moin/WorkingWithTime

In addition if you transmit dates with .000Z timezone to Google calendar it will ignore DST (Daylight Savings Time) for events that occur in EDT and others (so things will be off by an hour for parts of the year.)

Here is my fix: Assuming start_time and end_time are timezone aware datetime.datetime objects:

    timezone_string = start_datetime.strftime('%z')[0:3] + ":" + start_datetime.strftime('%z')[3:6]    
    start_time = start_datetime.strftime('%Y-%m-%dT%H:%M:%S' + timezone_string)
    end_time = end_datetime.strftime('%Y-%m-%dT%H:%M:%S' + timezone_string)

Note that stftime("%z") doesn't include that ":" character to separate the hours/minutes in the offset that Google's calendar API requires.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号