Can we convert string to date in python?

Can we convert string to date in python?
Educative Answers Team

Python provides the strptime() method, in its datetime class, to convert a string representation of the​ date/time into a date object.

Syntax

The syntax for the strptime() method is:

Code

The code snippet below illustrates the usage of the strptime() method in Python:

from datetime import datetime

date_time_str = '18/09/19 01:55:19'

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


print ("The type of the date is now",  type(date_time_obj))
print ("The date is", date_time_obj)

The strptime() method will not work if the string argument is not consistent with the format parameter. This is shown below​:

from datetime import datetime

date_time_str = '180919 015519'

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


print ("The type of the date is now",  type(date_time_obj))
print ("The date is", date_time_obj)

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.
Can we convert string to 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 in Python?

Convert Python String to Date: Python'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..

How do I convert a string to a date?

Java String to Date Example.
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);.
System.out.println(sDate1+"\t"+date1);.

How do I convert a string to a timestamp in Python?

Approach:.
import datetime is use to import the date and time modules..
After importing date time module next step is to accept date string as an input and then store it into a variable..
Then we use strptime method. ... .
We convert date and time string into a date object..
Then we use timetuple() to convert date object into tuple..

How do I convert a value to a date in Python?

Example 15: Format date using strftime().
%Y - year [0001,..., 2018, 2019,..., 9999].
%m - month [01, 02, ..., 11, 12].
%d - day [01, 02, ..., 30, 31].
%H - hour [00, 01, ..., 22, 23..
%M - minute [00, 01, ..., 58, 59].
%S - second [00, 01, ..., 58, 59].