Search code examples
pythonsqldatetimetypestransition

How to convert string (date) data to datetime or int or any other mathematical things to operate?


below is my code and whatever i do, i couldn't do the transition. 'Date' is always coming as string and i want to change it to a datetime object. I tried to use pd.to_datetime or pd.to_numeric or etc. Also I tried to do it in SQL but it gives an error about explicit conversion. Please help me.

GIP_SST1 = "SELECT  DATEADD(Day, ((cast(t1.[Pos] as Numeric)-1)-(cast(t1.[Pos] as Numeric)-1) % 24)/24, t1.[BillingDate]) AS Date, "\
+"(cast(t1.[Pos] as Numeric)-1) % 24 as Hour, "\
+"cast(t1.[InQty] as float ) as Value "\
+"FROM [PmumWebService].[dbo].[tbl_GetUzlastirmaSonucFinal] t1 "\
+"left join  [PmumWebService].[dbo].[tbl_ParentCompanies] t2  on t1.Party = t2.EtsoCode "\
+"Where BillingDate between '"+StartDate+"' and '"+EndDate+"' and AgreementId ='TALGIP' and Party='40X000000000282U' "

GIP_SST1 = pd.read_sql(GIP_SST1,connection)
GIP_SST1["Date"] = pd.to_datetime(GIP_SST1["Date"], format = "%Y-%m-%d")

for i in GIP_SST1.columns:
    print(type(GIP_SST[i][0]))


<class 'str'>
<class 'numpy.int64'>
<class 'numpy.float64'>

print(GIP_SST1.head())
        Date  Hour  Value
0 2019-10-01   0.0    0.0
1 2019-10-01   1.0    0.0
2 2019-10-01   2.0    0.0
3 2019-10-01   3.0    0.0
4 2019-10-01   4.0    0.0`

Solution

  • You can try this

    from datetime import datetime
    from dateutil.parser import parse
    import pandas as pd
    
    war_start = '2019-01-01'
    datetime.strptime(war_start, '%Y-%m-%d')