syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me

Question:
In Python how do I convert a string to a datetime?

A common use-case for working with Python Machine Learning technology is the simple step of converting a string to a datetime object.

The script below offers a simple demo:
# str2datetime_demo.py

import datetime

mystr = '2009-05-01 00:45:00'

mydt = datetime.datetime.strptime(mystr, "%Y-%m-%d %H:%M:%S")

# Now that I have the string converted into a date,
# I can use strftime() to convert the date back into intersting strings.

# I can answer questions like the ones listed below:

print('The date is:')
print(mydt)

print('The year of this date is:')
print(mydt.strftime('%Y'))

print('The month-name of this date is:')
print(mydt.strftime('%B'))

print('The week number of the year of this date is:')
print(mydt.strftime('%j'))

print('The day-name of this date is:')
print(mydt.strftime('%A'))

print('The weekday name of this date is:')
print(mydt.strftime('%w'))
Here is a screendump from the above script:

dan@hp ~/cjb4/fx $ 
dan@hp ~/cjb4/fx $ python /tmp/str2datetime_demo.py
The date is:
2009-05-01 00:45:00
The year of this date is:
2009
The month-name of this date is:
May
The week number of the year of this date is:
121
The day-name of this date is:
Friday
The weekday name of this date is:
5
dan@hp ~/cjb4/fx $ 
dan@hp ~/cjb4/fx $ 
A site that I often visit when I work with datetime objects is listed below:

http://strftime.org


syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me