-2

I have a date with format in 'yyyy-dd-mm'. How do I convert to 'yyyy-mm-dd' format, been bit of a struggle with strftime and strptime!

Assuming the date is '1919-01-12', I want to see it in the format '1919-12-01'.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
TRex
  • 445
  • 5
  • 14
  • 2
    What exactly do you mean by *"bit of a struggle"*? Give a [mre]. – jonrsharpe Mar 28 '21 at 21:02
  • 2
    Does this answer your question? [How to convert a date string to different format](https://stackoverflow.com/questions/14524322/how-to-convert-a-date-string-to-different-format) – miquelvir Mar 28 '21 at 21:11
  • @miquelvir yes that was helpful as well ! thanks again – TRex Mar 30 '21 at 09:33

2 Answers2

2
from datetime import datetime

date = '1919-01-12'
formatted_date = datetime.strptime(date, '%Y-%d-%m').strftime('%Y-%m-%d')

datetime.strptime(date, '%Y-%d-%m') creates a datetime object from a string, .strftime('%Y-%m-%d') formats the datetime as a string accoring to the specified pattern

absoup
  • 418
  • 3
  • 8
1

try this code

import datetime
print (datetime.datetime.strptime("1919-01-12", "%Y-%d-%m").strftime("%Y-%m-%d"))