Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a string into a date object and get year, month and day separately?

If I have lets say this string "2008-12-12 19:21:10" how can I convert it into a date and get the year, month and day from that created object separately?

like image 347
Ivan Juarez Avatar asked Sep 14 '12 18:09

Ivan Juarez


People also ask

How do I convert a Date to a datetime object?

You can use the datetime module's combine method to combine a date and a time to create a datetime object. If you have a date object and not a time object, you can initialize the time object to minimum using the datetime object(minimum time means midnight).


1 Answers

Use the datetime.datetime.strptime() function:

from datetime import datetime dt = datetime.strptime(datestring, '%Y-%m-%d %H:%M:%S') 

Now you have a datetime.datetime object, and it has .year, .month and .day attributes:

>>> from datetime import datetime >>> datestring = "2008-12-12 19:21:10" >>> dt = datetime.strptime(datestring, '%Y-%m-%d %H:%M:%S') >>> print dt.year, dt.month, dt.day 2008 12 12 
like image 83
Martijn Pieters Avatar answered Sep 24 '22 15:09

Martijn Pieters