简体   繁体   中英

Convert an RFC 3339 nano time to a standard Python timestamp

Is there an easy way to convert an RFC 3339 nano time into a regular Python timestamp?

For example, time = '2022-07-14T12:01:25.225089838+08:00', I found a way using datetime

from datetime import datetime

time = '2022-07-14T12:01:25.225089+08:00'
date = datetime.fromisoformat(time)  # good

time = '2022-07-14T12:01:25.225089838+08:00'
date = datetime.fromisoformat(time)  # error

It works with string like '2022-07-14T12:01:25.225089+08:00', but it doesn't work with the time above.

from datetime.fromisoformat docs :

Caution: This does not support parsing arbitrary ISO 8601 strings - it is only intended as the inverse operation of datetime.isoformat(). A more full-featured ISO 8601 parser, dateutil.parser.isoparse is available in the third-party package dateutil.


dateutil 's isoparse will do the job:

from dateutil.parser import isoparse

time = '2022-07-14T12:01:25.225089838+08:00'
date = isoparse(time) 

print(date)
# 2022-07-14 12:01:25.225089+08:00

print(repr(date))
# datetime.datetime(2022, 7, 14, 12, 1, 25, 225089, tzinfo=tzoffset(None, 28800))

Note: it doesn't round to microseconds, it just slices off the last 3 decimal places. So basically, if you're dealing with a standardized format like RFC 3339, you can do the slicing yourself like

from datetime import datetime

time = '2022-07-14T12:01:25.225089838+08:00'
date = datetime.fromisoformat(time[:-9] + time[-6:])

print(date)
# 2022-07-14 12:01:25.225089+08:00

There are a few ways to do it. Depends on what is the input format and how you define an easy way. There are actually many post asking similar issues you have. I'll post a few at the end for your reference if you are interested and please check next time before posting.

The main issue of datetime object is that it only holds 6 digit after second. You will need a different data structure to save it if you want to preserve all of the digits.

If you are ok with cutting off with 6 digit, FObersteiner's answer is perfect. Another methodology is vanilla datetime string parsing

from datetime import datetime
date = '2022-07-14T12:01:25.225089838+08:00'.removesuffix('+08:00')
x = datetime.strptime( date[:-3], '%Y-%m-%dT%H:%M:%S.%f')

If you would like to preserve all the digits. You may want to create your own class extending from the datetime class or create some function for it.

  1. Convert an RFC 3339 time to a standard Python timestamp

  2. Parsing datetime strings containing nanoseconds

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