简体   繁体   中英

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. 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.

>>> 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.

I don't know if this might be helpful, but it returned the timestamp of 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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