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

Abhinav Agarwal

Graduate Student at Northwestern University
linkedin profile url

I come from Northwestern University, which is ranked 9th in the US. Although the high-quality academics at school taught me all the basics I needed, obtaining practical experience was a challenge.... Read More

Relevant Projects

Build a Speech-Text Transcriptor with Nvidia Quartznet Model
In this Deep Learning Project, you will leverage transfer learning from Nvidia QuartzNet pre-trained models to develop a speech-to-text transcriptor.

Deep Learning Project for Text Detection in Images using Python
CV2 Text Detection Code for Images using Python -Build a CRNN deep learning model to predict the single-line text in a given image.

NLP Project to Build a Resume Parser in Python using Spacy
Use the popular Spacy NLP python library for OCR and text classification to build a Resume Parser in Python.

Deep Learning Project for Beginners with Source Code Part 1
Learn to implement deep neural networks in Python .

NLP Project for Multi Class Text Classification using BERT Model
In this NLP Project, you will learn how to build a multi-class text classification model using using the pre-trained BERT model.

Learn to Build a Polynomial Regression Model from Scratch
In this Machine Learning Regression project, you will learn to build a polynomial regression model to predict points scored by the sports team.

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.

Classification Projects on Machine Learning for Beginners - 1
Classification ML Project for Beginners - A Hands-On Approach to Implementing Different Types of Classification Algorithms in Machine Learning for Predictive Modelling

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.

Loan Eligibility Prediction Project using Machine learning on GCP
Loan Eligibility Prediction Project - Use SQL and Python to build a predictive model on GCP to determine whether an application requesting loan is eligible or not.