Python Forum

Full Version: String to Date format
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi

I have a date column as below. the date is in this format "January 5, 2020"
I want this date in to mm/dd/YYY format -- 01/05/2020. How I can convert using python?

Date
January 5, 2020
January 10, 2022
January 12, 2020
As poster over strftime().
>>> from datetime import datetime
>>> 
>>> d = 'January 5, 2020'
>>> date_obj = datetime.strptime(d, '%B %d, %Y')
>>> date_obj
datetime.datetime(2020, 1, 5, 0, 0)
>>> print(date_obj)
2020-01-05 00:00:0 
Or simpler use pendulum,advisable to use if need dealing with time zones.
>>> import pendulum
>>> 
>>> d = 'January 5, 2020'
>>> dt = pendulum.parse(d, strict=False)
>>> dt
DateTime(2020, 1, 5, 0, 0, 0, tzinfo=Timezone('UTC'))
>>> print(dt)
2020-01-05T00:00:00+00:00
>>> 
>>> dt.to_date_string()
'2020-01-05'
>>> dt.to_iso8601_string()
'2020-01-05T00:00:00Z'