+

Python | Pandas.to_datetime ()

When a CSV file is imported and a data frame is created, the Date-Time objects in the file are read as a string object rather than a Date-Time object, and therefore it is very difficult to perform operations such as time difference above the line, not a Date-Time object. , to_datetime() Pandas to_datetime() helps to convert a Date time string to a Python datetime object.

Syntax:

pandas.to_datetime (arg, errors = `raise`, dayfirst = False, yearfirst = False , utc = None, box = True, format = None, exact = True, unit = None, infer_datetime_format = False, origin = `unix`, cache = False)

 
Parameters :

arg: An integer, string, float, list or dict object to convert in to Date time object.
dayfirst: Boolean value, places day first if True.
yearfirst: Boolean value, places year first if True.
utc: Boolean value, Returns time in UTC if True.
format: String input to tell position of day, month and year.

Return type: Date, time, series of objects.

For a link to the CSV file in use, click here .

Example # 1: a string for a date
The following example reads a csv file and converts a date column in a data frame to a Date Time object from a string object.

# pandas package import

import pandas as pd

 
# create a data frame from CSV file

data = pd. read_csv ( "todatetime.csv" )

 
# overwriting data after format change

data [ "Date" ] = pd.to_datetime (data [ " Date " ])

 
# data information
data.info ()

 
# display
data

Output:
As shown in the picture, the Data Type of Date column was an object, but after using to_datetime () it was converted to a date and time object.

Before the operation

After operations

Example # 2: Exception when time conversion
A time object can also be converted using this method. But since there is no date in the Time column, Pandas will automatically fill in today`s date in this case.

# package import pandas

import pandas as pd

 
# create a data frame from a CSV file

data = pd.read_csv ( "todatetime.csv" )

 
# overwrite data after modification format

data [ "Time" ] = pd.to_datetime (data [ " Time " ])

  
# data information
data.info ()

 
# display
data

Output:
As shown in the output, the date (2018-07-07) which is today`s date has already been added with a Date time object.

Get Solution for free from DataCamp guru