How to Convert String to Datetime64 in Python?

This tutorial guides you through the process of converting strings to datetime64 objects in Python effortlessly. | ProjectPro

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 the form of strings but how to convert it into a 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 oftentimes 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 tutorial demonstrates how to convert date strings to the datetime format.

What is the datetime64 format in NumPy?

NumPy's datetime64 is a specialized data type for handling dates and times. It provides a flexible and efficient way to work with temporal data, allowing for precise calculations and manipulations. The 'datetime64' type is based on a 64-bit integer representing time in nanoseconds, providing a balance between precision and storage efficiency.

How to Convert String to Datetime? 

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, here are the various methods to convert a string to DateTime in Python. In this we will do this by using three different functions.

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 a string in format %Y-%m-%d. Then we tried to print it as a DateTime Stamp by using the 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 dates 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 the 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 the 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]

Example - How to Convert String to Datetime64?

The above example contains the string date "2022-03-08" which is converted to a datetime64 object using the np.datetime64() function. The output displays the conversion result, showcasing the simplicity of the process.

Example - How to Convert Python Datetime64 to String?

Converting a datetime64 object back to a string is equally straightforward. The numpy_datetime.astype(str) method accomplishes this task effortlessly. Let's illustrate this with an example:

Here, the datetime64 object is converted back to a string using the astype(str) method. This showcases the bidirectional flexibility of NumPy when working with datetime data.

How to Convert NumPy Datetime64 to Datetime?

While datetime64 provides excellent functionality, there may be scenarios where working with native Python datetime objects is preferable. NumPy facilitates this conversion through the numpy_datetime.tolist() method. 

For example - 

The above code example converts a datetime64 object to a Python datetime object using the tolist() method. This conversion enables seamless integration with other Python libraries and applications that utilize native datetime formats.

Become a Python Pro with ProjectPro! 

The conversion between string and datetime64 in NumPy helps you manipulate temporal data efficiently. So, whether you work with datasets, time series analysis, or any other time-related task, NumPy's datetime64 capabilities prove invaluable. ProjectPro is like a treasure chest filled with over 270 exciting projects related to data science and big data. It's not just about reading; it's about playing and experimenting with what you've learned. It also helps you practice and get better at using tools like Python, NumPy and Pandas in real-life situations. Instead of just reading about it, ProjectPro lets you try things out, and make learning super fun! So, why stick to boring textbooks when you can explore ProjectPro Repository to make your learning experience awesome! 

Download Materials

What Users are saying..

profile image

Anand Kumpatla

Sr Data Scientist @ Doubleslash Software Solutions Pvt Ltd
linkedin profile url

ProjectPro is a unique platform and helps many people in the industry to solve real-life problems with a step-by-step walkthrough of projects. A platform with some fantastic resources to gain... Read More

Relevant Projects

Build ARCH and GARCH Models in Time Series using Python
In this Project we will build an ARCH and a GARCH model using Python

Langchain Project for Customer Support App in Python
In this LLM Project, you will learn how to enhance customer support interactions through Large Language Models (LLMs), enabling intelligent, context-aware responses. This Langchain project aims to seamlessly integrate LLM technology with databases, PDF knowledge bases, and audio processing agents to create a comprehensive customer support application.

Linear Regression Model Project in Python for Beginners Part 1
Machine Learning Linear Regression Project in Python to build a simple linear regression model and master the fundamentals of regression for beginners.

A/B Testing Approach for Comparing Performance of ML Models
The objective of this project is to compare the performance of BERT and DistilBERT models for building an efficient Question and Answering system. Using A/B testing approach, we explore the effectiveness and efficiency of both models and determine which one is better suited for Q&A tasks.

Build a Churn Prediction Model using Ensemble Learning
Learn how to build ensemble machine learning models like Random Forest, Adaboost, and Gradient Boosting for Customer Churn Prediction using Python

Build a Music Recommendation Algorithm using KKBox's Dataset
Music Recommendation Project using Machine Learning - Use the KKBox dataset to predict the chances of a user listening to a song again after their very first noticeable listening event.

Learn How to Build PyTorch Neural Networks from Scratch
In this deep learning project, you will learn how to build PyTorch neural networks from scratch.

Locality Sensitive Hashing Python Code for Look-Alike Modelling
In this deep learning project, you will find similar images (lookalikes) using deep learning and locality sensitive hashing to find customers who are most likely to click on an ad.

Build Real Estate Price Prediction Model with NLP and FastAPI
In this Real Estate Price Prediction Project, you will learn to build a real estate price prediction machine learning model and deploy it on Heroku using FastAPI Framework.

Recommender System Machine Learning Project for Beginners-1
Recommender System Machine Learning Project for Beginners - Learn how to design, implement and train a rule-based recommender system in Python