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?
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With