为什么Python日期时间.time有tzinfo参数吗?

2024-09-29 01:29:09 发布

您现在位置:Python中文网/ 问答频道 /正文

datetime,Python的内置模块,有一些类。在

但是我不能很好地理解datetime.time类的参数。在

time类有tzinfo参数,默认为None。在

我想知道time类为什么需要时区信息。在

对于datetime类,它有.astimezone方法,我们可以根据时区信息更改数据。但是time类没有.astimezone这样的方法。在

它是为datetime.combineclassmethod保留的吗?或者有关于时间和时区的重要故事吗?在


Tags: 模块数据方法none信息参数datetimetime
2条回答

time类使用tzinfo进行比较和操作。例如,美国/太平洋地区的上午9:00不等于美国/东部的上午9:00。此外,如果将aware时间与naiver时间进行比较,例如,将美国/太平洋地区的上午9:00与“上午9:00”进行比较,python可能会引发类型错误

来自the docs

comparison of time to time, where a is considered less than b when a precedes b in time. If one comparand is naive and the other is aware, TypeError is raised if an order comparison is attempted. For equality comparisons, naive instances are never equal to aware instances.

I want to know why time class needs timezone information.

我发现它很有用,例如,如果我们处理的是同一时间发生的事件,而不考虑日期(例如,计划的作业),并且需要在不同的时区显示、操作和比较。在

如何获得TZ感知的datetime.time对象

datetime.timetz()

Return time object with same hour, minute, second, microsecond, and tzinfo attributes. See also method time().

对于我的示例用例,我将使用datetime.datetime.timetz()从我的tz感知datetime.datetime对象中提取{}对象,它保存了tzinfo

这将适合datetime.time对象,而不是也包含日期信息的datetime.datetime对象。在

But time class have no method like .astimezone.

你不能只用时间来转换

至于没有time.astimezone()的原因,我想可能是因为没有日期,就无法猜测DST转换和其他非固定UTC偏移的影响。在

相关问题 更多 >