4

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()
AlexLordThorsen
  • 8,057
  • 5
  • 48
  • 103
  • 2
    Try `raw_datetime = raw_datetime.replace(tzinfo=dateutil.tz.tzlocal())`. I think datetimes are immutable. – Mikko Ohtamaa Mar 19 '15 at 04:59
  • Total the right answer. I'm a dumb. – AlexLordThorsen Mar 19 '15 at 05:03
  • 2
    unrelated: `dt = dt.replace(tzinfo=dateutil.tz.tzlocal()))` fails if the local timezone had different utc offset at `dt` time, [use `aware_dt = tzlocal.get_localzone().localize(naive_dt, is_dst=None) ` instead](http://stackoverflow.com/a/17365806/4279). – jfs Mar 19 '15 at 17:12
  • 2
    DO NOT USE datetime.replace(tzinfo= ) https://stackoverflow.com/questions/39759041/replace-tzinfo-and-print-with-localtime-amends-six-minutes – MrE Sep 13 '17 at 18:27

1 Answers1

8

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).

Matt
  • 724
  • 4
  • 11
  • 4
    datetime.replace(tzinfo= ) only works for UTC timezone, and fails in many other cases. Do not use. – MrE Sep 13 '17 at 18:28