Search code examples
pythondatedatetimetimestrptime

Python custom datetime(?) format handling


Let's say i have a string representing a time with number of day of the week:

For example '52300', which means 5th day of week(Friday), 23 Hours 00 Minutes.

How do i parse it to time or datetime object to add a timedelta(hours=3) and get it back to this strange format? Expected output is '60200' string.

I have tried:

tow_str = '52300'
tow = datetime.datetime.strptime(tow_str, "%w%H%M") + datetime.timedelta(hours=3)
print(tow.strftime("%w%H%M"))

which returns '20200' instead of '60200'


Solution

  • Parsing a date with %w accurately requires that you include the date itself, otherwise the date is set to 1900-01-01:

    >>> import datetime
    >>> tow_str = '52300'
    >>> datetime.datetime.strptime(tow_str, "%w%H%M")
    datetime.datetime(1900, 1, 1, 23, 0)
    

    and you always end up with 1 when formatting back to a string:

    >>> datetime.datetime.strptime(tow_str, "%w%H%M").strftime("%w%H%M")
    '12300'
    

    Without a date, %w is meaningless.

    You could produce a date from the weekday based on today's date, and only parse the time:

    def nearest_date_for_weekday(weekday):
        today = datetime.date.today()
        return today + datetime.timedelta(days=weekday - today.weekday())
    
    parsed_date = datetime.datetime.combine(
        nearest_date_for_weekday(int(tow_str[0])), 
        datetime.datetime.strptime(tow_str[1:], '%H%M').time())
    
    print parsed_date.strftime('%w%H%M')
    

    So this produces a complete datetime object, so formatting back to a string gives a meaningful value for %w.