pytz 和 astimezone() 不能应用于天真的日期时间

2023-07-03Python开发问题
39

本文介绍了pytz 和 astimezone() 不能应用于天真的日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个日期,我需要让它知道时区.

I have a date and I need to make it time zone aware.

local_tz = timezone('Asia/Tokyo')
start_date = '2012-09-27'
start_date = datetime.strptime(start_date, "%Y-%m-%d")   
start_date = start_date.astimezone(local_tz)


now_utc = datetime.now(timezone('UTC'))
local_now = now_utc.astimezone(local_tz)

我需要看看这是不是真的:

I need to find if this is true:

print start_date>local_now

但我收到此错误.

   start_date = start_date.astimezone(local_tz)
   ValueError: astimezone() cannot be applied to a naive datetime

我将 UTC 转换为东京没有问题.我需要在东京制作 start_date 时区感知广告.

I convert utc to tokyo with no issue. I need to make start_date timezone aware ad well in tokyo.

谢谢

推荐答案

对于 pytz 时区,使用他们的 .localize() 方法来转换一个幼稚的 datetime 对象与时区合二为一:

For pytz timezones, use their .localize() method to turn a naive datetime object into one with a timezone:

start_date = local_tz.localize(start_date)

对于没有 DST 转换的时区,.replace()将时区附加到天真的 datetime 对象的方法 通常也可以工作:

For timezones without a DST transition, the .replace() method to attach a timezone to a naive datetime object should normally also work:

start_date = start_date.replace(tzinfo=local_tz)

有关详细信息,请参阅 pytz 文档的本地化时间和日期算术.

See the localized times and date arithmetic of the pytz documentation for more details.

这篇关于pytz 和 astimezone() 不能应用于天真的日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11