How do i convert a date string to a date in python?

In this post, you’ll learn how to convert a Python string to a date, using the datetime module’s .strptime() method. Specifically, you’ll learn how to convert a string to a date and how to convert a Pandas column to datetime with this approach.

Working with dates, times, and timezones is a problem often faced in software development. The dates and times you receive back may not always be in a datetime format. It then becomes important to convert them.

The Quick Answer: Use Datetime’s strptime function

from datetime import datetime
date_string = '2021-12-31'
datetime = datetime.strptime(date_string, '%Y-%m-%d')

print(datetime)
# Returns: 2021-12-31 00:00:00

Let’s dive in!

  • Python Datetime Strptime: What is it?
  • How do you convert Python String to Date?
  • What are Datetime’s Format Codes?
  • Convert a Pandas column to datetime with strptime
  • Conclusion

Python Datetime Strptime: What is it?

Python’s datetime module comes built into your Python installation, meaning you don’t need to worry about installing it.

The datetime module comes with three main object types: datetime, and datetime. They can be considered self-explanatory, but just in case: date deals with dates, time deals with times, and datetime deals with both dates and times.

One of the very helpful methods that we can use within the datetime module is the strptime method that allows us to convert a string to a date (or in our case, a datetime).

The method looks like this:

datetime.strptime(date_string=, format=)
  • The date_string is the string that holds what we want to convert.
  • the format contains the format of the string. Learn more about it in the section on format code examples below.
How do i convert a date string to a date in python?
How to use strptime to convert python string to date

How do you convert Python String to Date?

In order to convert a Python string to a date (or datetime), we can use the datetime .strptime() method.

Let’s see how we can do this:

  1. We import the datetime object from the datetime module
  2. We pass the string into the .strptime() method, as well as its format
  3. We assign this to a new variable and print it out
from datetime import datetime

date_string = '2021-12-31 15:37'
datetime = datetime.strptime(date_string, '%Y-%m-%d %H:%M')

print(datetime)

# Returns: 2021-12-31 15:37:00

At first glance, these format codes may look a little funny. You’ll learn all about some different examples in the next section.

What are Datetime’s Format Codes?

The datetime module uses a specific format codes in order to convert a string to a datetime or a datetime to a string. In the list below, you’ll learn a number of the most important format codes that you’ll encounter:

  • %a: Weekday in the locale’s abbreviated name (e.g., Mon)
  • %A: Weekday in the locale’s full name (e.g., Monday)
  • %b: month as locale’s abbreviated name (e.g., Dec)
  • %B: month as locale’s full name (e.g., December)
  • %m: month as zero-padded decimal number (e.g., 01)
  • %d: day as a zero-padded decimal number (e.g., 09)
  • %y: year without century (e.g., 2021)
  • %Y: year with century (e.g., 21)

For example, if you’re given a string that looks like this: 'Monday June 3, 2021', you’d write '%A %B %d, %Y'

The important thing to know here is that characters like commas or colons need to be included as well. This may feel a bit unnatural but think of the format codes as placeholders.

To see the rest of the format codes, check out the official documentation here.

Convert a Pandas column to datetime with strptime

Pandas has a very helpful built-in tool called .to_datetime() to convert a column to, well, datetime. You can learn about it in details in this post here.

Let’s load this dataframe and see what it looks like:

import pandas as pd

df = pd.DataFrame.from_dict(
    {
        'Name': ['Jane', 'Melissa', 'John', 'Matt'],
        'Hire Date': ['2021-03-13', '2019-01-01', '2018-04-12', '2016-12-12'],
        'Gender': ['F', 'F', 'M', 'M']
    }
)

print(df)

This returns:

      Name   Hire Date Gender
0     Jane  2021-03-13      F
1  Melissa  2019-01-01      F
2     John  2018-04-12      M
3     Matt  2016-12-12      M

Now, let’s use the method to convert the Hire Date column to datetime:

df['Hire Date'] = pd.to_datetime(df['Hire Date'])

However, if you wanted to use the datetime .strptime method, you could apply the function to the entire column. Keep in mind, this isn’t efficient and the Pandas .to_datetime() method is much more efficient. Learn a bit more about the Pandas .apply() method in my post here.

df['Hire Date'] = df['Hire Date'].apply(lambda x: datetime.strptime(x, '%Y-%m-%d'))

Conclusion

In this post, you learned how to convert a Python string to date or datetime. You learned how the datetime strptime function works, what datetime format codes are, as well as how to handle string to date conversion in Pandas.

To learn more about the datetime strptime function, check out the official documentation here.

How do I convert a string to a date?

Let's see the simple code to convert String to Date in java..
import java.text.SimpleDateFormat;.
import java.util.Date;.
public class StringToDateExample1 {.
public static void main(String[] args)throws Exception {.
String sDate1="31/12/1998";.
Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(sDate1);.

How do you convert string to time in Python?

We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.

How do I change the date format in Python?

Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.

How do you parse a date in Python?

Python has a built-in method to parse dates, strptime . This example takes the string “2020–01–01 14:00” and parses it to a datetime object. The documentation for strptime provides a great overview of all format-string options.