How to convert python timestamp string to era?

I have the following line:

mytime = "2009-03-08T00:27:31.807Z" 

How to convert it to an era in python?

I tried:

 import time p = '%Y-%m-%dT%H:%M:%S' int(time.mktime(time.strptime(s, p))) 

But this does not work with 31.807Z .

+5
source share
4 answers

There are two parts:

 #!/usr/bin/env python from datetime import datetime utc_time = datetime.strptime("2009-03-08T00:27:31.807Z", "%Y-%m-%dT%H:%M:%S.%fZ") epoch_time = (utc_time - datetime(1970, 1, 1)).total_seconds() # -> 1236472051.807 

If you are sure that you want to ignore fractions of a second and get an integer result:

 #!/usr/bin/env python import time from calendar import timegm utc_time = time.strptime("2009-03-08T00:27:31.807Z", "%Y-%m-%dT%H:%M:%S.%fZ") epoch_time = timegm(utc_time) # -> 1236472051 

To support timestamps that correspond to a second value, such as Wed July 1 2:59:60 MSK 2015 , you can use a combination of time.strptime() and datetime (if you need seconds to jump, you should also consider microseconds) .

+12
source

You are missing .%fZ from your format string.

 p = '%Y-%m-%dT%H:%M:%S.%fZ' 

The correct way to convert to an era is to use datetime :

 from datetime import datetime p = '%Y-%m-%dT%H:%M:%S.%fZ' mytime = "2009-03-08T00:27:31.807Z" epoch = datetime(1970, 1, 1) print((datetime.strptime(mytime, p) - epoch).total_seconds()) 

Or call int if you want to ignore fractions.

+3
source

code:

 import datetime epoch = datetime.datetime(1970, 1, 1) mytime = "2009-03-08T00:27:31.807Z" myformat = "%Y-%m-%dT%H:%M:%S.%fZ" mydt = datetime.datetime.strptime(mytime, myformat) val = (mydt - epoch).total_seconds() print(val) > 1236472051.81 repr(val) > '1236472051.807' 

Notes:

+1
source

dateutil is the only library I found that correctly refers to the timezone offset identifier ( Z )

 pip install python-dateutil 

then

 from dateutil.parser import parse as date_parse print date_parse("2009-03-08T00:27:31.807Z") #get timestamp import calendar dt = date_parse("2009-03-08T00:27:31.807Z") timestamp1 = calendar.timegm(dt.timetuple()) 
+1
source

All Articles