How to convert STRING to DateTime in Python?

This recipe helps you convert STRING to DateTime in Python

Recipe Objective

Have you ever tried to work on datetime features in a dataset? It may look quite complicated to write datetime in its format, we can write date and time in form of strings but how to convert it in DateTime Stamp.

Converting strings to datetime objects in Python has become a common practice for data scientists especially in time series projects. Performing this is often times difficult due to various date formats - different month lengths, timezone variations etc.

To solve this, Python provides a specific data type called "datetime". But in many datasets, the dates might be represented as strings. This recipe demonstrates how to convert date strings to the datetime format.

datetime.strptime is the primary routine for parsing strings into datetimes. datetime.strptime(date_string, format)

Once you have your value in datetime objects, you can then extract specific components of the date such as the month, day, or year, all of which are available as the object's attributes.

So this is the recipe on how we can change string to DateTime in Python. In this we will do this by using three different functions.

Get Closer To Your Dream of Becoming a Data Scientist with 70+ Solved End-to-End ML Projects

Step 1 - Import the library

from datetime import datetime from dateutil.parser import parse import pandas as pd

We have imported datetime, parse and pandas. These three modules will be required.

Method 1 - Converting String into DateTime

We have first defined an object called date_start in which we have stored an string in format %Y-%m-%d. Then we have tried to print it as a DateTime Stamp by using function datetime.strptime. date_start = '2020-01-01' print(datetime.strptime(date_start, '%Y-%m-%d'))

Method 2 - Converting String into DateTime

We have created a list of date in the format %m/%d/%y and used parse function on all the values of date_list to convert it in the format of datetime64. date_list = ['2/7/2027', '6/8/2019', '10/25/2020', '6/29/2018', '2/5/2022'] print([parse(x) for x in date_list])

Explore More Data Science and Machine Learning Projects for Practice. Fast-Track Your Career Transition with ProjectPro

Method 3 - Converting String into DateTime

We have created a dictionary of values and passed in function pd.DataFrame to change it into a DataFrame with columns date and value. Then we have checked the data type in the dataframe (ie object) and to change it to datetime format, we have used pd.to_datetime function. data = {'date': ['2020-05-01 18:47:05.069722', '2016-01-01 18:47:05.119994', '2014-02-05 18:47:05.178768', '2018-04-02 18:47:05.230071', '2018-04-06 18:47:05.230071', '2019-08-02 18:47:05.280592', '2019-07-01 18:47:05.332662', '2011-03-03 18:47:05.385109', '2024-04-09 18:47:05.436523', '2015-04-04 18:47:05.486877'], 'value': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]} df = pd.DataFrame(data, columns = ['date', 'value']) print(df.dtypes) print(pd.to_datetime(df['date'])) print(pd.to_datetime(df['date']).dtypes) So the final output of all the methods are

2020-01-01 00:00:00

[datetime.datetime(2027, 2, 7, 0, 0), datetime.datetime(2019, 6, 8, 0, 0), datetime.datetime(2020, 10, 25, 0, 0), datetime.datetime(2018, 6, 29, 0, 0), datetime.datetime(2022, 2, 5, 0, 0)]

date     object
value     int64
dtype: object

0   2020-05-01 18:47:05.069722
1   2016-01-01 18:47:05.119994
2   2014-02-05 18:47:05.178768
3   2018-04-02 18:47:05.230071
4   2018-04-06 18:47:05.230071
5   2019-08-02 18:47:05.280592
6   2019-07-01 18:47:05.332662
7   2011-03-03 18:47:05.385109
8   2024-04-09 18:47:05.436523
9   2015-04-04 18:47:05.486877
Name: date, dtype: datetime64[ns]
datetime64[ns]

Download Materials

What Users are saying..

profile image

Jingwei Li

Graduate Research assistance at Stony Brook University
linkedin profile url

ProjectPro is an awesome platform that helps me learn much hands-on industrial experience with a step-by-step walkthrough of projects. There are two primary paths to learn: Data Science and Big Data.... Read More

Relevant Projects

Recommender System Machine Learning Project for Beginners-2
Recommender System Machine Learning Project for Beginners Part 2- Learn how to build a recommender system for market basket analysis using association rule mining.

Learn to Build an End-to-End Machine Learning Pipeline - Part 2
In this Machine Learning Project, you will learn how to build an end-to-end machine learning pipeline for predicting truck delays, incorporating Hopsworks' feature store and Weights and Biases for model experimentation.

Build an Image Segmentation Model using Amazon SageMaker
In this Machine Learning Project, you will learn to implement the UNet Architecture and build an Image Segmentation Model using Amazon SageMaker

Time Series Analysis with Facebook Prophet Python and Cesium
Time Series Analysis Project - Use the Facebook Prophet and Cesium Open Source Library for Time Series Forecasting in Python

Predict Churn for a Telecom company using Logistic Regression
Machine Learning Project in R- Predict the customer churn of telecom sector and find out the key drivers that lead to churn. Learn how the logistic regression model using R can be used to identify the customer churn in telecom dataset.

MLOps Project to Build Search Relevancy Algorithm with SBERT
In this MLOps SBERT project you will learn to build and deploy an accurate and scalable search algorithm on AWS using SBERT and ANNOY to enhance search relevancy in news articles.

Azure Text Analytics for Medical Search Engine Deployment
Microsoft Azure Project - Use Azure text analytics cognitive service to deploy a machine learning model into Azure Databricks

Build Multi Class Text Classification Models with RNN and LSTM
In this Deep Learning Project, you will use the customer complaints data about consumer financial products to build multi-class text classification models using RNN and LSTM.

Demand prediction of driver availability using multistep time series analysis
In this supervised learning machine learning project, you will predict the availability of a driver in a specific area by using multi step time series analysis.

LLM Project to Build and Fine Tune a Large Language Model
In this LLM project for beginners, you will learn to build a knowledge-grounded chatbot using LLM's and learn how to fine tune it.