morfizm (morfizm) wrote,

Python datetime WTF

Looks like getting formatted datetime string with current timezone is a disaster in Python.
Here is the shortest version of WTF code I could come up with:

import time, datetime
def get_date_str():
    tz = '%+4.4d' % ((-time.timezone/(60*60))*100) 
    return'%Y-%m-%d %H:%M') + tz

def get_date_str(dt):
    tz = -time.timezone//60
    tz0 = '+' if tz >= 0 else '-'
    tz1 = '%.2d' % (abs(tz)//60)
    tz2 = '%.2d' % (abs(tz)%60)
    return dt.strftime('%%Y-%%m-%%d %%H:%%M%s%s%s' % (tz0, tz1, tz2))
Update: в предыдущей версии (зачёркнуто) был баг в случае странных timezones, вроде +0545.
Tags: software development

Recent Posts from This Journal

  • Post a new comment


    default userpic

    Your reply will be screened

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.

Recent Posts from This Journal