curious_cosmo
curious_cosmo

Reputation: 1214

Increment times if date has changed?

I have a list of strings, and one of them looks like this:

'Thu Jun 18 19:58:02 2015
 ...many lines of data...
 txup: 19:59:47 txdown: 20:05:22
 rxup: 21:43:17 rxdown: 22:13:01'

But another may look like this:

'Fri Jun 19 23:12:12 2015
 ...many lines of data...
 txup: 23:39:47 txdown: 23:57:22
 rxup: 00:01:17 rxdown: 01:13:01'

As you can see, in some cases a time might cross midnight. When that happens, using the above string as an example, the date associated with that time would now be Jun 20 instead of Jun 19.

I need to write a code that compares the 'rxup' time with the date/time at the start of the string and recognizes if and when it increases by a day because it passed midnight (all relative to the date/time at the beginning).

If it hasn't crossed midnight and is thus the same day, then I'm done. But if it has crossed midnight, I need to take the difference between that time and the time at the beginning probably as a timedelta object, and add that increment onto a copy of the time at the beginning. How would I do this?

Upvotes: 1

Views: 98

Answers (2)

Oleh Rybalchenko
Oleh Rybalchenko

Reputation: 8059

Assuming that rxup always appears after txdown, but less than 24 hours later, you can compare it like below:

# txdown, rxup - datetimes with respective times, date part doesn't matters
# associated_date - datetime associated with string
if rxup.time() < txdown.time():
    associated_date += datetime.timedelta(days=1)

Upvotes: 1

bipll
bipll

Reputation: 11940

If the times grow monotonously you can simply compare them in lexicographic order. '00:01:17' is obviously less than '23:39:47', so each time next timestamp is less than the current one, you increment the date.

Upvotes: 1

Related Questions