如何将字符串(日期)数据转换为 datetime 或 int 或任何其他数学运算的东西?
How to convert string (date) data to datetime or int or any other mathematical things to operate?
下面是我的代码,无论我做什么,我都无法进行转换。 'Date' 总是以字符串形式出现,我想将其更改为日期时间对象。我尝试使用 pd.to_datetime 或 pd.to_numeric 等。我也尝试在 SQL 中使用它,但它给出了有关显式转换的错误。请帮助我。
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`
你可以试试这个
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')
下面是我的代码,无论我做什么,我都无法进行转换。 'Date' 总是以字符串形式出现,我想将其更改为日期时间对象。我尝试使用 pd.to_datetime 或 pd.to_numeric 等。我也尝试在 SQL 中使用它,但它给出了有关显式转换的错误。请帮助我。
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`
你可以试试这个
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')