简体   繁体   English

Python-给定一个时区感知的datetime对象,如何获取未时区的UTC datetime对象?

[英]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. 我对Python中的datetime.datetime.utcnow()返回时区未使用的datetime对象感到困惑。 I would expect it to be timezone-aware with UTC as its timezone, but whatever. 我希望它将以UTC为时区,但是可以识别时区。 In order to convert this to a timezone-aware datetime object I would do the following: 为了将其转换为可识别时区的datetime对象,我将执行以下操作:

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. 给定一个可识别时区的datetime对象,我想回到对应的时区朴素的UTC datetime对象。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用时区感知和时区天真日期时间列处理 CSV - Handling CSV with timezone-aware and timezone-naive datetime column FutureWarning:使用“datetime64[ns]”dtype 将时区感知的 DatetimeArray 转换为时区天真的 ndarray - FutureWarning: Converting timezone-aware DatetimeArray to timezone-naive ndarray with 'datetime64[ns]' dtype 我可以有一个时区感知的datetime.date对象吗? - Can I have a timezone-aware datetime.date object? 如何从Python日期时间获得时区感知的年,月,日,小时等? - How can I get the timezone-aware year, month, day, hour etc. from a Python datetime? Django:如何以时区感知方式检索日期时间 - Django: How to retrieve datetime as timezone-aware 如何使时区感知日期时间 object - How to make a timezone aware datetime object 为什么具有不同时区的时区感知和时区感知日期时间 object 会产生相同的 unix 时间戳? - Why do a timezone-unaware and a timezone-aware datetime object with a different timezone yield the same unix-timestamp? 如何使用和不使用SQLAlchemy处理MySQL上的时区感知日期时间对象的“超出范围”警告 - How do I handle “out of range” warnings for timezone-aware datetime objects on MySQL with and without SQLAlchemy 将datetime obj转换为可识别时区的datetime - Convert datetime obj to timezone-aware datetime 如何在 python 中创建时区感知时间 object - How to create a timezone-aware time object in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM