pandas.to_datetime() – Examples

2. pandas.to_datetime() Syntax & Examples

Below is the syntax of the pandas.to_datetime() method.

# Pandas.to_datetime() syntax
pandas.to_datetime(arg, errors='raise', dayfirst=False, yearfirst=False, 
     utc=None, format=None, exact=True, unit=None, 
     infer_datetime_format=False, origin='unix', cache=True)
  • arg – An integer, string, float, list, or DataFrame/dict_like object to convert into a Datetime object.
  • errors – Take values raise, ignore or coerce. if ‘raise’ used, raise a KeyError when a dict-like mapper, index, or columns contains labels that are not present in the Index being transformed. Default set to ignore.
  • dayfirst – default set False, Boolean value places day first if True.
  • yearfirst – Boolean value places year first if True, the default set False.
  • utc – Boolean value, Returns the time in UTC DatetimeIndex if True.
  • format – String input to tell the position of the day, month, and year. default set None.
  • exact – Boolean value, If True, require an exact format match. – If False, allow the format to match anywhere in the target string.
  • infer_datetime_formatbool – If True and no format is given, attempt to infer the format of the datetime strings based on the first non-NaN element. the default set False.

Now, let’s create a DataFrame with a few rows and columns, execute above examples and validate results. Our DataFrame contains column names Courses, Fee, Duration, Discount and Inserted.

# Pandas.to_datetime() Syntax & Examples
import pandas as pd
from datetime import datetime, timedelta
from pandas import DataFrame
df = DataFrame.from_dict(
     'Fee' :[20000,25000,30000],
     'Inserted': ["11/22/2021, 10:39:24","11/22/2021, 10:39:24","11/22/2021, 10:39:24"]},

Yields below output. Note that Inserted column on the DataFrame has datetime in the format of "%m/%d/%Y, %H:%M:%S"

# Output:
  Courses    Fee Duration Discount              Inserted
A   Spark  20000   30days     1000  11/22/2021, 10:39:24
B  Hadoop  25000   40days     2500  11/22/2021, 10:39:24
C  pandas  30000   35days     1500  11/22/2021, 10:39:24

Naveen (NNK)

I am Naveen (NNK) working as a Principal Engineer. I am a seasoned Apache Spark Engineer with a passion for harnessing the power of big data and distributed computing to drive innovation and deliver data-driven insights. I love to design, optimize, and managing Apache Spark-based solutions that transform raw data into actionable intelligence. I am also passion about sharing my knowledge in Apache Spark, Hive, PySpark, R etc.

Leave a Reply

You are currently viewing pandas.to_datetime() – Examples