DatCra
DatCra

Reputation: 373

Convert different date format string into datetime format

I have a column of date with different format of date

publish_date = ["Feb. 2, 2000", "June 4, 1989", "Mar. 13, 2018"]

I was using strptime() to convert one type of string, how can I convert multiple formats of date in the same column?

type 1: %b %d, %Y

type 2: %B %d, %Y

Upvotes: 0

Views: 60

Answers (2)

Rakesh
Rakesh

Reputation: 82765

You can also use dateutil

Demo:

from dateutil.parser import parse 
publish_date = ["Feb. 2, 2000", "June 4, 1989", "Mar. 13, 2018"]
for date in publish_date:
    print( parse(date) )

Output:

2000-02-02 00:00:00
1989-06-04 00:00:00
2018-03-13 00:00:00

Upvotes: 2

Peter Gibson
Peter Gibson

Reputation: 19544

You could use the 3rd party dateparser module

Install with pip install dateparser, then

>>> import dateparser
>>> publish_date = ["Feb. 2, 2000", "June 4, 1989", "Mar. 13, 2018"]
>>> for d in publish_date:
...     print(dateparser.parse(d))
... 
2000-02-02 00:00:00
1989-06-04 00:00:00
2018-03-13 00:00:00

dateparser accepts a huge range of formats, but you can restrict it to just the ones you're interested in if you like

>>> for d in publish_date:
...     print(dateparser.parse(d, date_formats=['%b %d, %Y', '%B %d, %Y']))
... 
2000-02-02 00:00:00
1989-06-04 00:00:00
2018-03-13 00:00:00

Upvotes: 2

Related Questions