Python dt.replace(tzinfo=) doesn't change timezome

10,584

Just a simple oversight, replace doesn't modify the calling object but instead returns a new object with the value replaced.

datetime.replace:

Return a date with the same value, except for those parameters given new values by whichever keyword arguments are specified. For example, if d == date(2002, 12, 31), then d.replace(day=26) == date(2002, 12, 26).

Share:
10,584
AlexLordThorsen
Author by

AlexLordThorsen

Software Developer and part time circus performer. I get to say "This is my circus, these are my monkeys."

Updated on June 14, 2022

Comments

  • AlexLordThorsen
    AlexLordThorsen almost 2 years

    Why doesn't replace modify the tzinfo object when it recieves a valid timezone object?

    I'm attempting to add the local time to timestamps that didn't specify a timezone.

    if raw_datetime.tzinfo is None:
        print(raw_datetime)
        print(raw_datetime.tzinfo)
        raw_datetime.replace(tzinfo=dateutil.tz.tzlocal())
        print(raw_datetime.tzinfo, dateutil.tz.tzutc())
    

    According to the documentation I should be able to change the tzinfo attribute with a valid datetime

    https://docs.python.org/2/library/datetime.html#datetime.date.replace

    But I'm obviously doing something wrong because the tzinfo object is still None.

    2000-04-25 12:57:00
    None
    None tzutc()