Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse and combine date and time (leap seconds) from strings - python

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.

like image 679
greencup Avatar asked Apr 07 '26 09:04

greencup


1 Answers

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.

like image 117
jfs Avatar answered Apr 10 '26 02:04

jfs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!