[Python] Python: datetime tzinfo time zone names documentation

Discussão em 'Python' iniciado por Stack, Agosto 5, 2025.

  1. Stack

    Stack Membro Participativo

    I have a date that I build:

    from datetime import datetime
    from datetime import tzinfo
    test = '2013-03-27 23:05'
    test2 = datetime.strptime(test,'%Y-%m-%d %H:%M')
    >>> test2
    datetime.datetime(2013, 3, 27, 23, 5)

    >>> test2.replace(tzinfo=EST)
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    NameError: name 'EST' is not defined

    >> test2.replace(tzinfo=UTC)
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    NameError: name 'UTC' is not defined


    I can't find documentation on the list of time zone names that I can assign to tzinfo in the replace.tzinfo= call.

    I have read through the following and there is nothing:

    http://docs.python.org/2/library/datetime.html#tzinfo-objects

    Edit: The solution provided by unutbu got the following:

    >>> test = '2013-03-27 00:05'
    >>> test
    '2013-03-27 00:05'

    >>> test2 = dt.datetime.strp(test, '%Y-%m-%d %H:%M')
    >>> test2
    datetime.datetime(2013, 3, 27, 0, 5)

    >>> est = pytz.timezone('US/Eastern')
    >>> utc = pytz.utc
    >>> print(est.localize(test2))
    2013-03-27 00:05:00-04:00
    >>> print(utc.localize(test2))
    2013-03-27 00:05:00+00:00

    >>> print(est.localize(test2,is_dst=False))
    2013-03-27 00:05:00-04:00
    >>> print(est.localize(test2,is_dst=True))
    2013-03-27 00:05:00-04:00
    >>>


    As you can see even when I provide the is_dst= flag the offset is still '-04:00', which is EDT and not EST.

    The documentation shows the following:

    If you insist on working with local times, this library provides a facility for constructing them unambiguously: http://pytz.sourceforge.net/#problems-with-localtime

    >>> loc_dt = datetime(2002, 10, 27, 1, 30, 00)
    >>> est_dt = eastern.localize(loc_dt, is_dst=True)
    >>> edt_dt = eastern.localize(loc_dt, is_dst=False)
    >>> print(est_dt.strftime(fmt) + ' / ' + edt_dt.strftime(fmt))
    2002-10-27 01:30:00 EDT-0400 / 2002-10-27 01:30:00 EST-0500


    eastern was defined earlier in the documentation as eastern = timezone('US/Eastern')

    This seems to indicate that the is_dst= flag should further specify whether day light savings is specified or not. I would appreciate help on why this isn't working in my case.

    Continue reading...

Compartilhe esta Página