Miller
Miller

Reputation: 145

Convert to epoch in python

I have got a time in this format 2019-05-01T01:59 and I need to convert it into epoch.

 pattern = '%Y-%m-%d %H:%M'
 datefromsec = int(time.mktime(time.strptime(datefrom, pattern)))

I am trying with this code but I am getting this error
time data u'2019-05-01T01:59' does not match format.

Can anyone please help me out.

Upvotes: 0

Views: 59

Answers (2)

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20500

Your pattern was incorrect. It should have been %Y-%m-%dT%H:%M instead of %Y-%m-%d %H:%M.
You can then calculate epoch as follows .

import datetime

pattern = '%Y-%m-%dT%H:%M'
s = '2019-05-01T01:59'

dt_obj = datetime.datetime.strptime(s,pattern)

#Get epoch date
epoch = datetime.datetime.utcfromtimestamp(0)

#Print epoch
print((dt_obj - epoch).total_seconds() * 1000.0)

The output will be 1556675940000.0

Upvotes: 1

Nils
Nils

Reputation: 2695

Your pattern is wrong - you are missing the T

Solution:

pattern = '%Y-%m-%dT%H:%M'

Upvotes: 2

Related Questions