Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

convert
string
date
python

How to convert a string to a date in Python

Educative Answers Team

Python provides the strptime() method, in its datetime class, to convert a string representation of the​ date/time into a date object.

svg viewer

Syntax

The syntax for the strptime() method is:

svg viewer

Code

The code snippet below illustrates the usage of the strptime() method in Python:

from datetime import datetime

date_time_str = '18/09/19 01:55:19'

date_time_obj = datetime.strptime(date_time_str, '%d/%m/%y %H:%M:%S')


print ("The type of the date is now",  type(date_time_obj))
print ("The date is", date_time_obj)

The strptime() method will not work if the string argument is not consistent with the format parameter. This is shown below​:

from datetime import datetime

date_time_str = '180919 015519'

date_time_obj = datetime.strptime(date_time_str, '%d/%m/%y %H:%M:%S')


print ("The type of the date is now",  type(date_time_obj))
print ("The date is", date_time_obj)

RELATED TAGS

convert
string
date
python
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses