Python日期时间与时间模块之间的差异

问题:Python日期时间与时间模块之间的差异

我试图弄清楚datetimetime模块之间的区别,以及每个模块的用途。

我知道datetime提供日期和时间。该time模块的用途是什么?

将理解示例,并且将特别关注与时区有关的差异。

I am trying to figure out the differences between the datetime and time modules, and what each should be used for.

I know that datetime provides both dates and time. What is the use of the time module?

Examples would be appreciated and differences concerning timezones would especially be of interest.


回答 0

time模块主要用于处理unix时间戳;表示为一个浮点数,以距unix纪元的秒数​​为单位。该datetime模块可以支持许多相同的操作,但是提供了更多的面向对象的类型集,并且对时区的支持有限。

the time module is principally for working with unix time stamps; expressed as a floating point number taken to be seconds since the unix epoch. the datetime module can support many of the same operations, but provides a more object oriented set of types, and also has some limited support for time zones.


回答 1

坚决time防止DST歧义。

专门使用系统time模块而不是datetime模块,以防止夏令时(DST)引起歧义

转换为任何时间格式(包括本地时间)都非常容易:

import time
t = time.time()

time.strftime('%Y-%m-%d %H:%M %Z', time.localtime(t))
'2019-05-27 12:03 CEST'

time.strftime('%Y-%m-%d %H:%M %Z', time.gmtime(t))
'2019-05-27 10:03 GMT'

time.time()是一个浮点数,表示自系统纪元以来的时间(以秒为单位)。time.time()非常适合明确的时间戳记。

如果系统另外运行了网络时间协议(NTP)守护程序,那么最终将获得相当可靠的时基。

这是该模块的文档time

Stick to time to prevent DST ambiguity.

Use exclusively the system time module instead of the datetime module to prevent ambiguity issues with daylight savings time (DST).

Conversion to any time format, including local time, is pretty easy:

import time
t = time.time()

time.strftime('%Y-%m-%d %H:%M %Z', time.localtime(t))
'2019-05-27 12:03 CEST'

time.strftime('%Y-%m-%d %H:%M %Z', time.gmtime(t))
'2019-05-27 10:03 GMT'

time.time() is a floating point number representing the time in seconds since the system epoch. time.time() is ideal for unambiguous time stamping.

If the system additionally runs the network time protocol (NTP) dæmon, one ends up with a pretty solid time base.

Here is the documentation of the time module.


回答 2

当您只需要特定记录的时间时,可以使用时间模块-假设您每天有一个单独的表/文件用于交易,那么您只需要时间。但是,时间数据类型通常用于存储2个时间点之间的时间

这也可以使用datetime完成,但是如果我们只处理特定日期的时间,则可以使用time模块。

日期时间用于存储特定数据和记录时间。就像在出租公司里一样。截止日期将是datetime数据类型。

The time module can be used when you just need the time of a particular record – like lets say you have a seperate table/file for the transactions for each day, then you would just need the time. However the time datatype is usually used to store the time difference between 2 points of time.

This can also be done using datetime, but if we are only dealing with time for a particular day, then time module can be used.

Datetime is used to store a particular data and time for a record. Like in a rental agency. The due date would be a datetime datatype.


回答 3

如果您对时区感兴趣,则应考虑使用pytz。

If you are interested in timezones, you should consider the use of pytz.