-4

I have this string (It's come from a variable. as a example, st_date)

'2015-01-28 03:00:00' 

and I want to parse the date and convert to type:date

datetime.date 2015-01-28 

from it.. How could I do that?

Chamal
  • 235
  • 1
  • 7
  • 13
  • Docu... https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime – Mathias Jan 26 '15 at 06:52
  • possible duplicate of [How to parse ISO formatted date in python?](http://stackoverflow.com/questions/127803/how-to-parse-iso-formatted-date-in-python) – Mathias Jan 26 '15 at 06:53
  • No. My question is about parsing and converting both in same cord. I didn't get correct answer from it.. But I got it from here.. Thank You.. – Chamal Jan 26 '15 at 09:49

7 Answers7

3

Use datetime.strptime() which takes two arguments, your date as a string and the format you want.

from datetime import datetime
my_date = datetime.strptime('2015-01-28 03:00:00', '%Y-%m-%d %H:%M:%S')
my_date.year
>> 2015
Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
1
import datetime
import time
date_str_obj = '2015-01-28 03:00:00'
date_date_obj = datetime.datetime.strptime(date_str_obj, '%Y-%m-%d %I:%M:%f')
rkatkam
  • 2,634
  • 3
  • 18
  • 29
1

Just read the docs https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime

from datetime import datetime

a = '2015-01-28 03:00:00'
print datetime.strptime(a[:10], '%Y-%m-%d')
Pavel Reznikov
  • 2,968
  • 1
  • 18
  • 17
0

Use the strptime() function.

datetime.datetime.strptime('2015-01-28 03:00:00','%Y-%m-%d %H:%M:%S') #24-hour clock
datetime.datetime.strptime('2015-01-28 03:00:00','%Y-%m-%d %I:%M:%S') #12-hour clock
Anirudh Ajith
  • 887
  • 1
  • 5
  • 15
John Hua
  • 1,400
  • 9
  • 15
0

You can use easy_date to make it easy:

import date_converter
my_date = date_converter.string_to_date('2015-01-28 03:00:00', '%Y-%m-%d %H:%M:%S')
Raphael Amoedo
  • 4,233
  • 4
  • 28
  • 37
0
from datetime import datetime
date = datetime.strptime('2015-01-28 03:00:00','%Y-%m-%d %H:%M:%S')
date.date()
Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
Bhautik
  • 21
  • 3
-1

Use dateutil:

import dateutil.parser
dateutil.parser.parse('2015-01-28 03:00:00').date()
>>datetime.date(2015, 1, 28)
D-fence
  • 22
  • 1