Lulabelle95
Lulabelle95

Reputation: 57

Flip the order of a date string

I have a list that I need input into this function: '11h00', '5-11-2019', 'iXicoZe', 'Drones' but the function only accepts if the date is written like this: '11h00', '2019-11-2019', 'iXicoZe', 'Drones'

def dateFromString(datestr):
    datestr=datestr.strip()
    return date(int(datestr[:2]), int(datestr[3:5]), int(datestr[6:10]))

Upvotes: 1

Views: 311

Answers (2)

rivamarco
rivamarco

Reputation: 767

Supposing you want the date in Y-m-d and not 2019-11-2019 that is no-sense, you can use datetime

from datetime import datetime

old_date = datetime.strptime('5-11-2019', '%d-%m-%Y')
new_date_str = old_date.strftime('%Y-%m-%-d')

The new date is 2019-11-5, so the reversed date

Edit: be careful putting '%Y-%m-%-d' and not '%Y-%m-%d', the additional - is necessary to exclude the leading zero in the day. Don't know why my answer was edited.

Upvotes: 1

kaya3
kaya3

Reputation: 51093

Split on hyphens, reverse, then join with hyphens:

def reverse_date_string(s):
    return '-'.join(reversed(s.split('-')))

Example:

>>> reverse_date_string('5-11-2019')
'2019-11-5'

Upvotes: 1

Related Questions