简体   繁体   English

如何将POSIX日期/时间转换为ISO并在Python中再次转换

[英]How to convert POSIX date/time to ISO and back again in Python

I am trying to convert some arbitrary date/time strings using the Python dateparser module. 我正在尝试使用Python dateparser模块转换一些任意的日期/时间字符串。 When I omit time zone information, the following happens: 当我省略时区信息时,会发生以下情况:

>>> import dateparser
>>> import time
>>> myctime = time.ctime(1500)
>>> myctime
'Wed Dec 31 16:25:00 1969'
>>> mytime = dateparser.parse(myctime)
>>> mytime
datetime.datetime(1969, 12, 31, 16, 25)
>>> mytime.timestamp()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument

A way I can work around the above is by specifying a time zone to the parser, as follows: 解决上述问题的一种方法是,为解析器指定一个时区,如下所示:

>>> mytime = parse(myctime, settings={'TIMEZONE': 'UTC', 'RETURN_AS_TIMEZONE_AWARE': True})
>>> mytime
datetime.datetime(1969, 12, 31, 16, 25, tzinfo=<UTC>)

But then I try to turn this back in to a timestamp and I do not get my initial expected value of 1500 back. 但是,然后我尝试将其重新设置为时间戳,但没有得到1500初始初始期望值。

>>> mytime.timestamp()
-27300.0

What am I doing wrong? 我究竟做错了什么? It seems pretty clear that it's converting the timestamp to some other time zone, but I don't want it to do that, I want it to give me UTC all the way. 似乎很显然,它将时间戳转换为其他时区,但是我不希望这样做,我希望它一直给我UTC。

I don't know if this might be helpful, but it returned the timestamp of 1500. 我不知道这是否有帮助,但是返回了1500的时间戳。

>>> from datetime import datetime, timezone
>>> t = datetime.utcfromtimestamp(1500)
>>> t
datetime.datetime(1970, 1, 1, 0, 25)
>>> t.replace(tzinfo=timezone.utc).timestamp()
1500.0

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

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