;

How to Convert String Date to DateTime Object in Python


Tutorialsrack 03/03/2021 Python

In this article, you will learn how to convert string Datetime to Datetime in python. Handling DateTime is the most common problem that we faced in software development. But in python, there is a built-in datetime module for dealing with dates and times.

Python strptime()

We are using a method called strptime().This function is available in both datetime and time modules to parse a string to DateTime and time objects respectively.

The syntax for datetime Module

The syntax for datetime Module

datetime.strptime(date_string, format)

The syntax for time Module

The syntax for time Module
time.strptime(time_string, format)

This method takes two arguments: the first argument is the string representation of the date-time and the second argument is the format of the input string. Both the arguments are mandatory and should be a string.

Python strptime() format directives

The directives of the string format codes are listed here for your reference as follow:

Directive

Description

Example Output

%a

Weekday as locale’s abbreviated name.

Sun, Mon, …, Sat (en_US)

So, Mo, …, Sa (de_DE)

%A

Weekday as locale’s full name.

Sunday, Monday, …, Saturday (en_US)

Sonntag, Montag, …, Samstag (de_DE)

%w

Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.

0, 1, 2, 3, 4, 5, 6

%d

Day of the month as a zero-padded decimal number.

01, 02, …, 31

%b

Month as locale’s abbreviated name.

Jan, Feb, …, Dec (en_US)

Jan, Feb, …, Dez (de_DE)

%B

Month as locale’s full name.

January, February, …, December (en_US)

Januar, Februar, …, Dezember (de_DE)

%m

Month as a zero-padded decimal number.

01, 02 … 12

%y

A year without century as a zero-padded decimal number.

01, 02, … 99

%Y

The year with century as a decimal number.

0001, 0002, … , 9999

%H

Hour (24-hour clock) as a zero-padded decimal number.

01, 02, … , 23

%I

Hour (12-hour clock) as a zero-padded decimal number.

01, 02, … , 12

%p

Locale’s equivalent of either AM or PM.

AM, PM (en_US)

am, pm (de_DE)

%M

Minute as a zero-padded decimal number.

01, 02, … , 59

%S

Second as a zero-padded decimal number.

01, 02, … , 59

%f

Microsecond as a decimal number, zero-padded on the left.

000000, 000001, …, 999999

Not applicable with the time module.

%z

UTC offset in the form ±HHMM[SS] (empty string if the object is naive).

(empty), +0000, -0400, +1030

%Z

Time zone name (empty string if the object is naive).

(empty), UTC, IST, CST

%j

Day of the year as a zero-padded decimal number.

001, 002, …, 366

%U

Week number of the year (Sunday as the first day of the week) as a zero-padded decimal number.

All days in a new year preceding the first Sunday are considered to be in week 0.

00, 01, …, 53

%W

Week number of the year (Monday as the first day of the week) as a decimal number.

All days in a new year preceding the first Monday are considered to be in week 0.

00, 01, …, 53

%c

Locale’s appropriate date and time representation.

Tue Aug 16 21:30:00 1988 (en_US)

Di 16 Aug 21:30:00 1988 (de_DE)

%x

Locale’s appropriate date representation.

08/16/88 (None)

08/16/1988 (en_US)

16.08.1988 (de_DE)

%X

Locale’s appropriate time representation.

21:30:00 (en_US)

21:30:00 (de_DE)

%%

A literal ‘%’ character.

%

Python datetime.strptime() Examples

Here are the examples to convert string datetime to datetime object in Python.

Example 1: String datetime to datetime

Example 1: String datetime to datetime
from datetime import datetime

datetime_str = '02/23/21 13:55:26'

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

# print Datetime Object
print(type(datetime_object))

# printed in default format
print(datetime_object)
Output

<class 'datetime.datetime'>

2021-02-23 13:55:26

Example 2: Another example of string datetime to datetime

Example 2: Another example of string datetime to datetime
from datetime import datetime

dateString = "7-May-2021 13:55:26"

datetime_object = datetime.strptime(dateString, "%u-%b-%Y %H:%M:%S")

# print Datetime Object
print(type(datetime_object))

# printed in default format
print(datetime_object)
Output

<class 'datetime.datetime'>

2021-05-01 13:55:26

Example 3: string date to date

Example 3: string date to date
from datetime import datetime
date_str = '02-23-2021'

date_object = datetime.strptime(date_str, '%m-%d-%Y').date()

# print datetime object
print(type(date_object))

# printed in default formatting
print(date_object)
Output

<class 'datetime.date'>

2021-02-23

Example 4: String time to time object

Example 4: String time to time object
from datetime import datetime

time_str = '13::55::26'
time_object = datetime.strptime(time_str, '%H::%M::%S').time()

# print time object
print(type(time_object))

# printed in default format
print(time_object)
Output

<class 'datetime.time'>

13:55:26

Python strptime() ValueError Examples

Example 1: Python datetime.strptime() ValueError Example

Example 1: Python datetime.strptime() ValueError Example
from datetime import datetime
datetime_str = '09/19/18 13:55:26'

try:
    datetime_object = datetime.strptime(datetime_str, '%m/%d/%y')
except ValueError as ve:
    print('ValueError Raised:', ve)
Output

ValueError Raised: unconverted data remains:  13:55:26

Example 2: Python time.strptime() ValueError Example

Example 1: Python datetime.strptime() ValueError Example
import time
time_str = '99::55::26'

try:
    time_object = time.strptime(time_str, '%H::%M::%S')
except ValueError as ve:
    print('ValueError:', ve)
Output

ValueError: time data '99::55::26' does not match format '%H::%M::%S'

I hope this article will help you to understand how to convert the string Datetime to Datetime object in python.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags