mineral
mineral

Reputation: 529

How can I convert float column to datetime?

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.

Upvotes: 3

Views: 2782

Answers (2)

Cognisun Inc
Cognisun Inc

Reputation: 446

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

Upvotes: 4

popeye
popeye

Reputation: 886

You might try something like this:

r_datetime = pd.to_datetime({'year': df['year'], 
                             'month': df['month'], 
                             df['day'].name: df['day'], # if you don't want to type column names explicitly. But will have to type it in any case.
                             'hour': df['hour'], 
                             'minutes': df['minutes']}, 
                            format="%y%M%d%h%m")

Read more in the docs.

Upvotes: 1

Related Questions