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

Gautam Vermani

Data Consultant at Confidential
linkedin profile url

Having worked in the field of Data Science, I wanted to explore how I can implement projects in other domains, So I thought of connecting with ProjectPro. A project that helped me absorb this topic... Read More

Relevant Projects

End-to-End Speech Emotion Recognition Project using ANN
Speech Emotion Recognition using RAVDESS Audio Dataset - Build an Artificial Neural Network Model to Classify Audio Data into various Emotions like Sad, Happy, Angry, and Neutral

Learn to Build a Neural network from Scratch using NumPy
In this deep learning project, you will learn to build a neural network from scratch using NumPy

Build an End-to-End AWS SageMaker Classification Model
MLOps on AWS SageMaker -Learn to Build an End-to-End Classification Model on SageMaker to predict a patient’s cause of death.

Digit Recognition using CNN for MNIST Dataset in Python
In this deep learning project, you will build a convolutional neural network using MNIST dataset for handwritten digit recognition.

Deep Learning Project for Time Series Forecasting in Python
Deep Learning for Time Series Forecasting in Python -A Hands-On Approach to Build Deep Learning Models (MLP, CNN, LSTM, and a Hybrid Model CNN-LSTM) on Time Series Data.

Build Deep Autoencoders Model for Anomaly Detection in Python
In this deep learning project , you will build and deploy a deep autoencoders model using Flask.

Predictive Analytics Project for Working Capital Optimization
In this Predictive Analytics Project, you will build a model to accurately forecast the timing of customer and supplier payments for optimizing working capital.

Customer Market Basket Analysis using Apriori and Fpgrowth algorithms
In this data science project, you will learn how to perform market basket analysis with the application of Apriori and FP growth algorithms based on the concept of association rule learning.

Deep Learning Project- Real-Time Fruit Detection using YOLOv4
In this deep learning project, you will learn to build an accurate, fast, and reliable real-time fruit detection system using the YOLOv4 object detection model for robotic harvesting platforms.

Loan Eligibility Prediction in Python using H2O.ai
In this loan prediction project you will build predictive models in Python using H2O.ai to predict if an applicant is able to repay the loan or not.