Skip to content Skip to sidebar Skip to footer

Convert String Date To Long In Python

I have data frame which has a column full of date-time of format yyyy-mm-ddTHH:MM:SSS.000Z For example, 2019-06-17T19:17:45.000Z. I want to convert this to long type (unix epoch ti

Solution 1:

Use module time:

import calendar
import time
calendar.timegm(time.strptime('2019-06-17T19:17:45.000Z', '%Y-%m-%dT%H:%M:%S.%fZ'))

Output: 1560799065

Solution 2:

using datetime module, fromisoformat (most likely fastest option) to parse the string and timestamp() to get POSIX seconds since the epoch:

from datetime import datetime
s = '2019-06-17T19:17:45.000Z'
ts = datetime.fromisoformat(s.replace('Z', '+00:00')).timestamp()
#  1560799065.0

or strptime with appropriate format code:

ts = datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f%z').timestamp()

...or dateutil's parser.parse (slower but even more convenient):

from dateutil.parser importparsets= parse(s).timestamp()

Post a Comment for "Convert String Date To Long In Python"