Home:ALL Converter>Python3 Timestamp to unix time (with sometime milliseconds)

Python3 Timestamp to unix time (with sometime milliseconds)

Ask Time:2018-01-17T04:44:01         Author:Jim

Json Formatter

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

Timestamp looks like this:

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?

Author:Jim,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/48289534/python3-timestamp-to-unix-time-with-sometime-milliseconds
pault :

Here is one way to handle your issue, using try and except:\n\nimport time\nimport datetime\n\ndef get_ts_unix(ts):\n try:\n tsUnix = time.mktime(\n datetime.datetime.strptime(ts, \"%Y-%m-%dT%H:%M:%S.%f\").timetuple()\n )\n except ValueError:\n tsUnix = time.mktime(\n datetime.datetime.strptime(ts, \"%Y-%m-%dT%H:%M:%S\").timetuple()\n )\n return tsUnix\n\n\nExample:\n\ntimestamps = ['2018-01-16T20:26:16.35', '2018-01-16T20:26:16']\nfor ts in timestamps:\n print(\"%-24s: %f\" % (ts, get_ts_unix(ts)))\n\n\nOutput:\n\n2018-01-16T20:26:16.35 : 1516152376.000000\n2018-01-16T20:26:16 : 1516152376.000000\n",