Open In App

Convert string to datetime in Python with timezone

Last Updated : 29 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite: Datetime module

In this article, we will learn how to get datetime object from time string using Python.

To convert a time string into datetime object, datetime.strptime() function of datetime module is used. This function returns datetime object. 

Syntax : datetime.strptime(date_string, format)

Parameters :

  • date_string : Specified time string containing of which datetime object is required. **Required
  • format : Abbreviation format of date_string

Returns : Returns the datetime object of given date_string

List of the acceptable format that can be passed to strptime():

Directive Meaning Output Format
%Y Year in four digits 2018, 2019 etc
%m Month as a zero-padded decimal number. 01, 02, …, 12
%b Month as locale’s abbreviated name. Jan, Feb, …, Dec
%d Day of the month as a zero-padded decimal number. 01, 02, …, 31
%H Hour (24-hour clock) as a zero-padded decimal number.  00, 01, …, 23
%I Hour (12-hour clock) as a zero-padded decimal number. 01, 02, …, 12
%M Minute as a zero-padded decimal number. 00, 01, …, 59
%S Second as a zero-padded decimal number. 00, 01, …, 59
%f Microsecond as a decimal number, zero-padded on the left. 000000, 000001, …, 999999
%p Locale’s equivalent of either AM or PM AM, PM, am, pm
%z UTC offset in the form ±HHMM +0000, -0400, +0530
%a Abbreviated weekday name. Sun, Mon, …

Example 1: Converting datetime string to datetime

Python3




# Python3 code to demonstrate
# Getting datetime object using a date_string
 
# importing datetime module
import datetime
 
# datestring for which datetime_obj required
date_string = '2021-09-01 15:27:05.004573 +0530'
print("string datetime: ")
print(date_string)
print("datestring class is :", type(date_string))
 
# using strptime() to get datetime object
datetime_obj = datetime.datetime.strptime(
    date_string, '%Y-%m-%d %H:%M:%S.%f %z')
 
print("converted to datetime:")
 
# Printing datetime
print(datetime_obj)
 
# Checking class of datetime_obj.
print("datetime_obj class is :", type(datetime_obj))


Output:

string datetime: 
2021-09-01 15:27:05.004573 +0530
datestring class is : <class 'str'>
converted to datetime:
2021-09-01 15:27:05.004573+05:30
datetime_obj class is : <class 'datetime.datetime'>

Example 2: Converting datetime string to datetime

Python3




# Python3 code to demonstrate
# Getting datetime object using a date_string
 
# importing datetime module
import datetime
 
# datestring for which datetime_obj required
date_string = '2021-09-01 15:27:05'
 
# using strptime() to get datetime object
datetime_obj = datetime.datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
 
# Printing datetime
print(datetime_obj)


Output:

2021-09-01 15:27:05

In this example, microseconds and time zone parts are removed from first example, so we need to remove microseconds and time zone abbreviations also from format string

Example 3: Converting datetime string to datetime

Python3




# Python3 code to demonstrate
# Getting datetime object using a date_string
 
# importing datetime module
import datetime
 
# datestring for which datetime_obj required
date_string = 'Sep 01 2021 03:27:05 PM'
 
# using strptime() to get datetime object
datetime_obj = datetime.datetime.strptime(date_string, '%b %d %Y %I:%M:%S %p')
 
# Printing datetime
print(datetime_obj)


Output:

2021-09-01 15:27:05



Previous Article
Next Article

Similar Reads

How to remove timezone information from DateTime object in Python
Timezone is defined as a geographical area or region throughout which standard time is observed. It basically refers to the local time of a region or country. Most of the time zones are offset from Coordinated Universal Time (UTC), the world’s standard for time zone. In this article, we will discuss how to remove timezone information from the DateT
2 min read
How to make a timezone aware datetime object in Python
In this example, we are going to see how to make a timezone-aware DateTime object in Python. Timezone-aware objects are Python DateTime or time objects that include timezone information. An aware object represents a specific moment in time that is not open to interpretation. Checking if an object is timezone aware or not: We can easily check if a d
4 min read
DateTime Timezone in SQLAlchemy
SQLAlchemy is a powerful and popular Python library that provides a flexible and efficient way to interact with databases. It uses the Object-Relational Mapping (ORM)tool, which acts as a bridge between the Python objects and the relational database. SQLALchemy provides a wide range of methods to work with databases, It provides a high level of abs
8 min read
Pandas Series dt.tz_convert | Change Timezone in DateTime Series
The dt.tz_convert() method converts tz-aware DateTime Series object from one time zone to another. Example C/C++ Code import pandas as pd sr = pd.Series(pd.date_range('2012-12-31 00:00', periods = 5, freq = 'D', tz = 'US / Central')) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx result = sr.dt.tz_convert(tz = 'Europe / Berlin')
2 min read
How to convert a Python datetime.datetime to excel serial date number
This article will discuss the conversion of a python datetime.datetime to an excel serial date number. The Excel "serial date" format is actually the number of days since 1900-01-00. The strftime() function is used to convert date and time objects to their string representation. It takes one or more inputs of formatted code and returns the string r
3 min read
Python DateTime - DateTime Class
DateTime class of the DateTime module as the name suggests contains information on both dates as well as time. Like a date object, DateTime assumes the current Gregorian calendar extended in both directions; like a time object, DateTime assumes there are exactly 3600*24 seconds in every day. But unlike the date class, the objects of the DateTime cl
5 min read
How to Fix - "datetime.datetime not JSON serializable" in Python?
In this article, we are going to learn how to fix the error "datetime.datetime not JSON serializable" in Python. datetime.datetime is a class in the Python datetime module that represents a single point in time. This class is not natively supported by the JSON (JavaScript Object Notation) format, which means that we cannot serialize a datetime.date
4 min read
How to convert timestamp string to datetime object in Python?
Python has a module named Datetime to work with dates and times. We did not need to install it separately. It is pre-installed with the Python package itself. A UNIX timestamp is several seconds between a particular date and January 1, 1970, at UTC. Input: "2023-07-21 10:30:45"Output: 2023-07-21 10:30:45Explanation: In This, We are converting a tim
2 min read
How to convert Python's .isoformat() string back into datetime object
In this article, we will learn how to convert Pythons .isoFormat() string back into a datetime object. Here we are using the current time and for that, we will store the current time in the current_time variable. The function now() of this module, does the job perfectly. Example: Getting current time C/C++ Code from datetime import datetime current
1 min read
Convert datetime string to YYYY-MM-DD-HH:MM:SS format in Python
In this article, we are going to convert the DateTime string into the %Y-%m-%d-%H:%M:%S format. For this task strptime() and strftime() function is used. strptime() is used to convert the DateTime string to DateTime in the format of year-month-day hours minutes and seconds Syntax: datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S") strftime() is used t
2 min read
Practice Tags :