• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Convert String to Datetime in Python

Convert String to Datetime in Python

Author: Aditya Raj
Last Updated: February 17, 2022

We normally keep dates in our text files or spreadsheets in the form of strings. While working with date and time in python, we often need to calculate the number of days spent or time spent between two events. In such calculations, we can use the python datetime module with the help of which we can store a date as a python object. In this article, we will discuss how we can convert a string to a datetime object in python.

What is Datetime in Python?

Python provides us datetime module to handle data related to time and date. It has many functions defined in it to calculate current time, time spent between two dates, etc. For instance, you can get the current date and time using the datetime.now() function as follows.

import datetime

today = datetime.datetime.now()
print("The Current Date and Time is:", today)

Output:

The Current Date and Time is: 2021-11-22 22:34:25.828339

The output of the datetime.now() function is a datetime object that has many attributes like the year, month, day, hour, minute, second, and microsecond. You can access each of the attributes as follows.

import datetime

today = datetime.datetime.now()
print("The Current Year is:", today.year)
print("The Current Month is:", today.month)
print("The Current Day is:", today.day)
print("The Current Hour is:", today.hour)
print("The Current Minute is:", today.minute)
print("The Current Second is:", today.second)
print("The Current Microsecond is:", today.microsecond)

Output:

The Current Year is: 2021
The Current Month is: 11
The Current Day is: 22
The Current Hour is: 22
The Current Minute is: 36
The Current Second is: 30
The Current Microsecond is: 972280

We can also create a datetime object using the datetime() constructor. It accepts the year, month, and day as its first, second, and, third argument and returns a datetime object as shown below.

import datetime

day = datetime.datetime(1999, 1, 20)
print("The Date is:", day)

Output:

The Date is: 1999-01-20 00:00:00

You can also pass the hour, minute, second, microsecond, and timezone parameters to the datetime() constructor as subsequent parameters after day in the same order. These are optional parameters and hour, minute, second, and microsecond has a default value 0. The timezone has a default value of None.

How to Convert String to Datetime in Python?

Instead of directly creating a date object, we can also convert a string to a datetime object in python. We can do so using the datetime.strptime() method.

The datetime.strptime() method accepts a string containing date as its first input argument and a string containing the format of date as its second input argument. After execution, it returns a datetime object as shown below.

import datetime

input_string = "1999-01-20"
print("The input string is:",input_string)
date_format = "%Y-%m-%d"  # %Y for year, %m for month and %d for day
day = datetime.datetime.strptime(input_string, date_format)
print("The Date is:", day)

Output:

The input string is: 1999-01-20
The Date is: 1999-01-20 00:00:00

We can also specify other formats for the input strings and convert them into datetime objects as shown in the following example.

import datetime

input_string = "1999/01/20"
print("The input string is:",input_string)
date_format = "%Y/%m/%d"  # %Y for year, %m for month and %d for day
day = datetime.datetime.strptime(input_string, date_format)
print("The Date is:", day)
input_string = "20-01-1999"
print("The input string is:",input_string)
date_format = "%d-%m-%Y"  # %Y for year, %m for month and %d for day
day = datetime.datetime.strptime(input_string, date_format)
print("The Date is:", day)
input_string = "20/01/1999"
print("The input string is:",input_string)
date_format = "%d/%m/%Y"  # %Y for year, %m for month and %d for day
day = datetime.datetime.strptime(input_string, date_format)
print("The Date is:", day)

Output:

The input string is: 1999/01/20
The Date is: 1999-01-20 00:00:00
The input string is: 20-01-1999
The Date is: 1999-01-20 00:00:00
The input string is: 20/01/1999
The Date is: 1999-01-20 00:00:00

Conclusion

In this article, we have discussed datetime objects in python. We also discussed how we can convert a string to a datetime object in python. To know more about strings, you can read this article on strings methods in python. You might also like this article on string concatenation in python.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us