Recipe: How to convert STRING to DateTime in Python?
DATA MUNGING PYTHON DATETIME

How to convert STRING to DateTime in Python?

This recipe helps you convert STRING to DateTime in Python

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/

In [1]:
## How to convert STRING to DateTime in Python
def Kickstarter_Example_53():
    print()
    print(format('How to convert STRING to DateTime in Python','*^82'))
    import warnings
    warnings.filterwarnings("ignore")

    # Load Libraries
    from datetime import datetime
    from dateutil.parser import parse
    import pandas as pd
    # Create a string variable with a datetime
    date_start = '2012-03-03'
    # Convert the string to datetime format
    print()
    print(datetime.strptime(date_start, '%Y-%m-%d'))
    # Create a list of strings as dates
    dates = ['7/2/2017', '8/6/2016', '11/13/2015', '5/26/2014', '5/2/2013']
    # Use parse() to attempt to auto-convert common string formats
    print()
    print(parse(date_start))

    print()
    print([parse(x) for x in dates])
    # Use parse, but designate that the day is first
    print()
    print(parse(date_start, dayfirst=True))

    # Create a dataframe
    data = {'date': ['2014-05-01 18:47:05.069722', '2014-05-01 18:47:05.119994',
                     '2014-05-02 18:47:05.178768', '2014-05-02 18:47:05.230071',
                     '2014-05-02 18:47:05.230071', '2014-05-02 18:47:05.280592',
                     '2014-05-03 18:47:05.332662', '2014-05-03 18:47:05.385109',
                     '2014-05-04 18:47:05.436523', '2014-05-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)
    # Convert df['date'] from string to datetime
    print()
    print(pd.to_datetime(df['date']))
    print(pd.to_datetime(df['date']).dtypes)
Kickstarter_Example_53()
*******************How to convert STRING to DateTime in Python********************

2012-03-03 00:00:00

2012-03-03 00:00:00

[datetime.datetime(2017, 7, 2, 0, 0), datetime.datetime(2016, 8, 6, 0, 0), datetime.datetime(2015, 11, 13, 0, 0), datetime.datetime(2014, 5, 26, 0, 0), datetime.datetime(2013, 5, 2, 0, 0)]

2012-03-03 00:00:00
date     object
value     int64
dtype: object

0   2014-05-01 18:47:05.069722
1   2014-05-01 18:47:05.119994
2   2014-05-02 18:47:05.178768
3   2014-05-02 18:47:05.230071
4   2014-05-02 18:47:05.230071
5   2014-05-02 18:47:05.280592
6   2014-05-03 18:47:05.332662
7   2014-05-03 18:47:05.385109
8   2014-05-04 18:47:05.436523
9   2014-05-04 18:47:05.486877
Name: date, dtype: datetime64[ns]
datetime64[ns]


Stuck at work?
Can't find the recipe you are looking for. Let us know and we will find an expert to create the recipe for you. Click here
Companies using this Recipe
1 developer from CGI
1 developer from HvH
1 developer from MudraCircle
1 developer from YASH Technologies
1 developer from Altimetrik
1 developer from Deep Learn Labs
1 developer from iPullRank
1 developer from SignDesk
1 developer from ANAC
1 developer from Fork Technologies