Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert float column to datetime?

Tags:

python

enter image description here

year: int64

month: float64

day: float64

hour: object

minute: object

I'm trying to make a date by combining these columns, but I keep getting an error. I don’t know what I should do.

Here are my code and error.

r_datetime = pd.to_datetime(
            str(int(df['year'])) \
            + '-' + str(int(df['month'])) \
            + '-' + str(int(df['day'])) \
            + ' ' + str(int(df['hour'])) \
            + ':' + str(int(df['minute']))
            )

TypeError: cannot convert the series to <class 'int'>

astype(str) is also getting error. i don't know what should i do.

Thank you for your help.

like image 572
mineral Avatar asked May 05 '26 22:05

mineral


1 Answers

Pandas Dataframe provides the freedom to change the data type of column values. We can change them from Integers to Float type, Integer to Datetime, String to Integer, Float to Datetime, etc. For converting float to DateTime we use pandas.to_datetime() function and following syntax is used :

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)

Converting one column from float to ‘yyyymmdd’ format using pandas.to_datetime()

import pandas as pd 
  
# Initializing the nested list  
# with Data set 
player_list = [[20200112.0,'Mathematics'],  
               [20200114.0,'English'], 
               [20200116.0,'Physics'],  
               [20200119.0,'Chemistry'], 
               [20200121.0,'French'],  
               [20200124.0,'Biology'],  
               [20200129.0,'Sanskrit']] 
  
# creating a pandas dataframe 
df = pd.DataFrame(player_list,columns=['Dates','Test']) 

  
# checking the type  
print(df.dtypes)
# converting the float to datetime format
df['Dates'] = pd.to_datetime(df['Dates'], format='%Y%m%d')  
  
# printing dataframe  
print(df) 
 
  
print(df.dtypes)

Read more in Docs

like image 51
Cognisun Inc Avatar answered May 08 '26 13:05

Cognisun Inc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!