2

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")
jophab
  • 4,942
  • 11
  • 42
  • 56
StackUser
  • 221
  • 2
  • 19
  • 2
    Take a look at the built in [strptime](https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior) – Lix May 04 '17 at 15:00
  • Possible duplicate of [Converting string into datetime](http://stackoverflow.com/questions/466345/converting-string-into-datetime) – David Cullen May 04 '17 at 16:22

4 Answers4

5

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.
mechanical_meat
  • 155,494
  • 24
  • 217
  • 209
3

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

omri_saadon
  • 9,513
  • 6
  • 31
  • 58
3

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)
naren
  • 13,825
  • 5
  • 37
  • 44
2
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

jophab
  • 4,942
  • 11
  • 42
  • 56