Python Pandas: Convert strings to time without date

Given a Pandas DataFrame, we have to convert strings to time without date.
Submitted by Pranit Sharma, on July 30, 2022

Prerequisite

  • Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.
  • A string is a group of characters, these characters may consist of all the lower case, upper case, and special characters present on the keyboard of a computer system. A string is a data type and the number of characters in a string is known as the length of the string.
  • On the other hand, Datetime is a library in python which is a collection of date and time. Inside Datetime, we can access date and time in any format, but usually, date is present in the format of "yy-mm-dd" and time is present in the format of "HH:MM:SS".

Convert strings to time without date in Pandas

To convert strings to time without date, we will use pandas.to_datetime() method which will help us to convert the type of string. Inside this method, we will pass a particular format of time.

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
    )

Let us understand with the help of an example,

Python program to convert strings to time without date

# Import pandas package
import pandas as pd

# import numpy package
import numpy as np

# Creating a dictionary
d = {'Time': ['12:00','23:43','07:08','18:09','15:15','00:01']}

# Creating a Dataframe
df = pd.DataFrame(d)

# Display the dataframe
print('Created DataFrame:\n',df,"\n")

# Converting Time column dtye to time
df['Time'] = pd.to_datetime(df['Time'], format='%H:%M').dt.time

# Display modified DataFrame
print("Modified DataFrame:\n",df)

Output

Example: Convert strings to time without date

Python Pandas Programs »



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.