Reputation: 4661
I have a date time object that looks like:
2015-31-12 00:34:00
where the second element (31) represents the day and the third element (12) represents the month. How do I swap day and month so that the date looks like:
2015-12-31 00:34:00
Upvotes: 1
Views: 5617
Reputation: 1123450
You'd parse the string into a datetime
object then format it again back to a string:
from datetime import datetime
result = datetime.strptime(inputstring, '%Y-%d-%m %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S')
Demo:
>>> from datetime import datetime
>>> inputstring = '2015-31-12 00:34:00'
>>> datetime.strptime(inputstring, '%Y-%d-%m %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S')
'2015-12-31 00:34:00'
So the datetime.strptime()
parses the string given a pattern, where you specify that the order is year-day-month, and datetime.strftime()
formats it back to a string, with the day and month positions swapped.
Upvotes: 4
Reputation: 9986
Use .strftime('%Y-%m-%d %H:%M:%S')
.
For example:
from datetime import datetime
formatted_date = datetime.today().strftime('%Y-%m-%d %H:%M:%S')
Upvotes: 1