Skip to content Skip to sidebar Skip to footer

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 ti

Solution 1:

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.

Post a Comment for "Python Custom Datetime(?) Format Handling"