简体   繁体   中英

Python - given a timezone-aware datetime object how do I get a timezone-naive UTC datetime object?

I'm bemused by the fact that in Python datetime.datetime.utcnow() returns a timezone-naive datetime object. I would expect it to be timezone-aware with UTC as its timezone, but whatever. In order to convert this to a timezone-aware datetime object I would do the following:

import pytz
from datetime import datetime

us_pacific = pytz.timezone('US/Pacific')
utc_now = datetime.utcnow()
pacific_now = us_pacific.fromutc(utc_now)

What I'd like to know now is how to go in the opposite direction. Given a timezone-aware datetime object, I'd like to get back to the corresponding timezone-naive UTC datetime object.

# First convert back to UTC
utc_time = pacific_now.astimezone(pytz.utc)

# Remove the timezone attribute to make it timezone-naive
utc_time = utc_time.replace(tzinfo=None)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM