[Dateutil] timezone question

Paul G paul at ganssle.io
Fri Dec 23 18:43:57 EST 2016


I think this is just a question of context. Time zone aware strings (for the most part) turn into timezone aware datetimes, timezone-naive strings turn into timezone-naive datetimes. Timezone-naive means that we don't know what the time zone is, so in some ways it's meaningless to compare it to a timezone aware time. It's similar to saying, "How much does that cost?" "It costs 5." - Is that 5 dollars? 5 yen? 5 rupees?

In the end, you have to make the decision about what time zone the naive datetimes represent. A few choices:

1. Assume that they are in whatever time zone the thing you are comparing them to. In that case, just drop the tzinfo from the aware datetimes:

dt_naive = dt_parsed.replace(tzinfo=None)

2. Assume that the naive datetimes are in YOUR local time:

tz_local = dateutil.tz.tzlocal()
dt_comparable = dt_parsed.replace(tzinfo=tz_local if dt_parsed.tzinfo is None else dt_parsed.tzinfo)

(Note that the way I've done this doesn't really account for ambiguous or imaginary times if that's important to you).

3. Assume that the naive datetimes are UTC:

tz_utc = dateutil.tz.tzutc()
dt_comparable = dt_parsed.replace(tzinfo=tz_utc if dt_parsed.tzinfo is None else dt_parsed.tzinfo)

In the end, you either need to assign a time zone to the naive datetimes you get or drop the time zone from the aware time zones you get.

If you are planning on working with time zone arithmetic and comparison and you decide to assign a time zone to the datetime objects, I recommend calling `.astimezone(dateutil.tz.tzutc())` on all timezone-aware datetimes once you have them in the right time zone, so you can more easily reason about datetime arithmetic by working in UTC.

On 12/23/2016 07:44 AM, Larry Martell wrote:
> I have a datetime that looks like this: '2016-11-11T18:10:09-05:00'
> and when I pass it to dateutil.parser.parse I get back this:
> 
> datetime.datetime(2016, 11, 11, 18, 10, 9, tzinfo=tzoffset(None, -18000))
> 
> And I have other datetimes like this: '2016-04-27T00:00:00', which
> went passed to dateutil.parser.parse of course does not return a
> datetime with the tzinfo.
> 
> I need to compare these datetimes, and if I do that I get the dreaded
> "can't compare offset-naive and offset-aware datetimes" error.
> 
> Is there a way I can get it back without the tzinfo, but instead with
> the offset applied to the data, so I can compare these 2?
> 
> TIA!
> _______________________________________________
> Dateutil mailing list
> Dateutil at python.org
> https://mail.python.org/mailman/listinfo/dateutil
> 

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/dateutil/attachments/20161223/ab138ef0/attachment.sig>


More information about the Dateutil mailing list