3

I parse a date (format: YYYY-MM-DD HH:MM:SS) from a data file which contains multiple lines of dates.

The problem is that the data contains leap seconds so i'm not able to use datetime. How can I take into account the leap seconds (0-60), so that at the end I would have the same result if I would have used datetime.strptime from the string with the format above (thus, date+time), please?

I have already tried with combine using date for the date and time for the time string. Is it the right way or are there some others?

Thanks in advance.

greencup
  • 41
  • 3

1 Answers1

1

Just use time.strptime():

#!/usr/bin/env python
import datetime as DT
import time
from calendar import timegm

utc_time_string = '2012-06-30 23:59:60'
utc_time_tuple = time.strptime(utc_time_string, "%Y-%m-%d %H:%M:%S")[:6]
utc_dt = DT.datetime(1970, 1, 1) + DT.timedelta(seconds=timegm(utc_time_tuple))
# -> datetime.datetime(2012, 7, 1, 0, 0)

If the input time is not in UTC then you could handle the leap second in the time_tuple manually e.g., the datetime module may raise ValueError if you pass the leap second directly or it may silently truncate 60 to 59 if it encounters a leap second in indirect (internal) calls.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670