2

I am trying to import experimental time data which is not really a time, date, or datetime according to the python formalism. It is a time-elapsed format as Dd HH:MM:SS.m where the first time point would be 0d 00:00:00.00 and a point 26 hours later would be 1d 02:00:00.00.

Is there a way to use the datetime module to extract the appropriate time information without hard-coding a string search for the day and adding a multiple of 24 to the hour counter?

martineau
  • 119,623
  • 25
  • 170
  • 301
Brooks
  • 21
  • 2
  • 1
    Sounds possible. What have you tried that isn't working? – martineau Dec 18 '18 at 22:00
  • The problem is that there is no flag for days as a unit of time, as far as I can tell, only for days as a date or datetime, meaning a zero padded day of the month (%d -> 01, 02, 03 etc) or a zero padded day of the year (%j -> 001, 002, 003 etc). The time format I am trying to convert does not 1) zero pad the day and 2) has 0d as an option which is not recognized by either day flag. – Brooks Dec 18 '18 at 22:25
  • This is very similar to the question at https://stackoverflow.com/questions/4628122/how-to-construct-a-timedelta-object-from-a-simple-string, so it might be worth looking at to see how to use the time parsing and `timedelta` class in `datetime` – Win Dec 18 '18 at 22:32
  • From the question linked by Win, wildwilhelm wrote a module to handle parsing multiple formats including the one originally posted by myself. https://stackoverflow.com/a/21498018/10808310 – Brooks Dec 18 '18 at 23:42

1 Answers1

1

To convert your 'odd' format to datetime.timedelta object try:

from datetime import timedelta
import re

input = '1d 02:00:00.00'


def to_timedelta(input):
    reg = re.search('([0-9])+d ([0-9]){2}:([0-9]){2}:([0-9]){2}\.([0-9]){2}', input)
    ints = tuple(int(t) for t in reg.groups())
    return timedelta(days=ints[0],
                     hours=ints[1],
                     minutes=ints[2],
                     seconds=ints[3],
                     milliseconds=ints[4])

td = to_timedelta(input)
print(td)
Petr Javorik
  • 1,695
  • 19
  • 25