Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()
like image 953
AlexLordThorsen Avatar asked Feb 10 '23 15:02

AlexLordThorsen


1 Answers

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

like image 102
Matt Avatar answered Feb 13 '23 10:02

Matt