StackUser
StackUser

Reputation: 253

Python Convert unusual date string to datetime format

I have date string like this:

Saturday, 30 Nov, 2013

So it is like Day_Name, Day, Month_Name_3_Letters, Year.

I wonder what is the best way to convert it to datetime format using python?

I using like this:

datetime.strptime((row[7].split(',')[1] + row[7].split(',')[2]).replace(' ',''), "%d%b%Y").strftime("%Y-%m-%d")

Upvotes: 2

Views: 2223

Answers (4)

naren
naren

Reputation: 15233

Why don't you use dateutil's parse ?

from dateutil import parser
parser.parse('Saturday, 30 Nov, 2013')
datetime.datetime(2013, 11, 30, 0, 0)

Upvotes: 3

mechanical_meat
mechanical_meat

Reputation: 169284

Use strptime:

 import datetime as dt
 s = 'Saturday, 30 Nov, 2013'
 d = dt.datetime.strptime(s,'%A, %d %b, %Y')

Result:

>>> d
datetime.datetime(2013, 11, 30, 0, 0)

As you'll see from the reference:

%A    Weekday as locale’s full name.
%d    Day of the month as a zero-padded decimal number.
%b    Month as locale’s abbreviated name.
%Y    Year with century as a decimal number.

Upvotes: 5

omri_saadon
omri_saadon

Reputation: 10621

You can use strptime function and initialize it as the following:

from datetime import datetime

datetime_object = datetime.strptime('Saturday, 30 Nov, 2013', '%A, %d %b, %Y')

print datetime_object

Conversely, the datetime.strptime() class method creates a datetime object from a string representing a date and time and a corresponding format string. datetime

In order to see how to use the formats and when, you can see strftime formats

Upvotes: 3

jophab
jophab

Reputation: 5509

from datetime import datetime

st='Saturday, 30 Nov, 2013'
print datetime.strptime(st,'%A, %d %b, %Y')

OUTPUT

2013-11-30 00:00:00

See strptime() at Tutorials point

Upvotes: 2

Related Questions