Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

datetime - How to convert python timestamp string to epoch?

I have the following string:

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

How do I convert it to epoch in python?

I tried:

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

But it does not work with the 31.807Z.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are two parts:

  1. Convert the time string into a broken-down time. See How to parse ISO formatted date in python?
  2. Convert the UTC time to "seconds since the Epoch" (POSIX timestamp).
#!/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 to 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 leap second such as Wed July 1 2:59:60 MSK 2015, you could use a combination of time.strptime() and datetime (if you care about leap seconds you should take into account the microseconds too).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...