How to convert STRING to DateTime in Python?
DATA MUNGING DATA CLEANING PYTHON MACHINE LEARNING RECIPES PANDAS CHEATSHEET     ALL TAGS

How to convert STRING to DateTime in Python?

How to convert STRING to DateTime in Python?

This recipe helps you convert STRING to DateTime in Python

0

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.

References: https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime http://strftime.org/

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.

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])

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]

Relevant Projects

German Credit Dataset Analysis to Classify Loan Applications
In this data science project, you will work with German credit dataset using classification techniques like Decision Tree, Neural Networks etc to classify loan applications using R.

Customer Churn Prediction Analysis using Ensemble Techniques
In this machine learning churn project, we implement a churn prediction model in python using ensemble techniques.

Ensemble Machine Learning Project - All State Insurance Claims Severity Prediction
In this ensemble machine learning project, we will predict what kind of claims an insurance company will get. This is implemented in python using ensemble machine learning algorithms.

Loan Eligibility Prediction using Gradient Boosting Classifier
This data science in python project predicts if a loan should be given to an applicant or not. We predict if the customer is eligible for loan based on several factors like credit score and past history.

Machine Learning or Predictive Models in IoT - Energy Prediction Use Case
In this machine learning and IoT project, we are going to test out the experimental data using various predictive models and train the models and break the energy usage.

Predict Employee Computer Access Needs in Python
Data Science Project in Python- Given his or her job role, predict employee access needs using amazon employee database.

Data Science Project - Instacart Market Basket Analysis
Data Science Project - Build a recommendation engine which will predict the products to be purchased by an Instacart consumer again.

Forecast Inventory demand using historical sales data in R
In this machine learning project, you will develop a machine learning model to accurately forecast inventory demand based on historical sales data.

Human Activity Recognition Using Multiclass Classification in Python
In this human activity recognition project, we use multiclass classification machine learning techniques to analyse fitness dataset from a smartphone tracker.

Zillow’s Home Value Prediction (Zestimate)
Data Science Project in R -Build a machine learning algorithm to predict the future sale prices of homes.