Site icon Spark By {Examples}

Pandas.to_datetime() – Examples

pandas to_datetime

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)

Now, let’s create a DataFrame with a few rows and columns, execute the 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(
    {'Courses':["Spark","Hadoop","Pandas"],
     'Fee' :[20000,25000,30000],
     'Duration':['30days','40days','35days'],
     'Discount':[1000,2500,1500],
     'Inserted': ["11/22/2021, 10:39:24","11/22/2021, 10:39:24","11/22/2021, 10:39:24"]},
     orient='index', 
     columns=['A','B','C']).T
print(df)

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
Exit mobile version