How to Convert Strings to Datetime in Python


In this example, we will get the methods to convert a string-format date to the date in a standard format with Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import datetime

# simple time conversion
datestr = '2017/01/01'
date = datetime.datetime.strptime(datestr, '%Y/%m/%d')
print('The standard date format for the string "%s": \n%s' % (datestr, date))

# complex time conversion
datestr = '03:24:05 11/05, 2019'
date = datetime.datetime.strptime(datestr, '%H:%M:%S %m/%d, %Y')
print('The standard date format for the string "%s": \n%s' % (datestr, date))

Output:

The standard date format for the string "2017/01/01":
2017-01-01 00:00:00
The standard date format for the string "03:24:05 11/05, 2019":
2019-11-05 03:24:05
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments