In this article we will discuss how to convert timestamp in different string formats to a datetime class object in Python.

String to datetime object using datetime.strptime()

Python’s datetime module provides a datetime class, which has a method to convert string to a datetime object i.e.

If accepts a string containing the timestamp and a format string containing the format codes representing the date time elements in date_string. It parses the string according to format codes and returns a datetime object created from it.

To use this import datetime class from datetime module i.e.

Let’s see some examples

Example 1:

Let’s convert a time string in format YYYY-MM-DDTHH::MM::SS.MICROS to a datetime object i.e.

Output:

Format string used here is : ‘%Y-%m-%dT%H::%M::%S.%f

Complete list of format code :

Format Codes Description Example
%d Day of the month as a zero-padded decimal number 01, 02, 03, 04 …, 31
%a Weekday as abbreviated name Sun, Mon, …, Sat
%A Weekday as full name Sunday, Monday, …, Saturday
%m Month as a zero-padded decimal number 01, 02, 03, 04 …, 12
%b Month as abbreviated name Jan, Feb, …, Dec
%B Month as full name January, February, …, December
%y Year without century as a zero-padded decimal number 00, 01, …, 99
%Y Year with century as a decimal number 0001, …, 2018, …, 9999
%H Hour (24-hour clock) as a zero-padded decimal number 01, 02, 03, 04 …, 23
%M Minute as a zero-padded decimal number 01, 02, 03, 04 …, 59
%S Second as a zero-padded decimal number 01, 02, 03, 04 …, 59
%f Microsecond as a decimal number, zero-padded on the left 000000, 000001, …, 999999
%I Hour (12-hour clock) as a zero-padded decimal number 01, 02, 03, 04 …, 12
%p Locale’s equivalent of either AM or PM AM , PM
%j Day of the year as a zero-padded decimal number 01, 02, 03, 04 …, 366

Let’s see some other examples :

Example 2:

Let’s convert a timestamp string in format DD/MM/YYYY HH::MM::SS to a datetime object i.e.

Output:

Example 3:

Create Date Time Object from date string only in ‘DD MMM YYYY‘ format

Output:

Example 4:

Create datetime Object from time string only in ‘HH:MM:SS AP‘ format

Output:

Example 5:

Create datetime Object from timestamp scattered in a text.

Some time our timestamp is embedded in a text like,

Let’s see how to convert timestamp in this string to a date time object with format codes mixed in text i.e.

Output:

Complete example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.