简体   繁体   中英

Python3 Timestamp to unix time (with sometime milliseconds)

I'm trying to convert a timestamp to unix time.

Timestamp looks like this:
2018-01-16T20:26:16.35

So now I use this code:

timestamp = '2018-01-16T20:26:16.35'
ts = timestamp.replace("T", " ")
tsUnix = time.mktime(datetime.datetime.strptime(ts, "%Y-%m-%d %H:%M:%S.%f").timetuple())

Sometime the api where get the timestamps from gives me the time without milliseconds .
It will result in a error, 'Does not match the format'. (Duh, %f is not in there)

Do I need to script a workaround or is there a function for this? And is there a better way to strip the "T" from the original timecode?

Here is one way to handle your issue, using try and except :

import time
import datetime

def get_ts_unix(ts):
    try:
        tsUnix = time.mktime(
            datetime.datetime.strptime(ts, "%Y-%m-%dT%H:%M:%S.%f").timetuple()
        )
    except ValueError:
        tsUnix = time.mktime(
            datetime.datetime.strptime(ts, "%Y-%m-%dT%H:%M:%S").timetuple()
        )
    return tsUnix

Example:

timestamps = ['2018-01-16T20:26:16.35', '2018-01-16T20:26:16']
for ts in timestamps:
    print("%-24s: %f" % (ts, get_ts_unix(ts)))

Output:

2018-01-16T20:26:16.35  : 1516152376.000000
2018-01-16T20:26:16     : 1516152376.000000

To skip the ts = timestamp.replace("T", " ") add a T in the format string

timestamp = '2018-01-16T20:26:16.35'
time.mktime(datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S.%f").timetuple())
# returns 1516130776.0

To fix the milliseconds you could use the python-dateutil package

from dateutil import parser

raw_timestamp = '2018-01-16T20:26:16.35'
parsed_time = parser.parse(raw_timestamp)
timestamp = parsed_time.timestamp()

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