vidhan
vidhan

Reputation: 129

Convert string to epoch time?

I have a string in this format '2016-06-15T12:52:05.623Z'. I want to calculate the number of seconds of this time since epoch.

How can I do that?

Upvotes: 1

Views: 2853

Answers (3)

pzp
pzp

Reputation: 6607

from datetime import datetime

my_date = '2016-06-15T12:52:05.623Z'
dtformat = '%Y-%m-%dT%H:%M:%S.%fZ'
d = datetime.strptime(my_date, dtformat)

epoch = datetime.utcfromtimestamp(0)

print (d - epoch).total_seconds()
# OUT: 1465995125.62

Upvotes: 1

Use time to return the timestamp from datetime:

import datetime
import time

date = datetime.datetime.strptime('2016-06-15T12:52:05.623Z', "%Y-%m-%dT%H:%M:%S.%fZ")
print time.mktime(date.timetuple())
>> 1466005925.0

Upvotes: 1

Simon Kirsten
Simon Kirsten

Reputation: 2577

In Python 3:

import dateutil.parser

t = dateutil.parser.parse("2016-06-15T12:52:05.623Z")
print(t.timestamp())

Upvotes: 4

Related Questions