Python 将日期提取为字符串
我想在python中设置一个日期范围,然后创建一个新的系列/列,并将日期格式化为字符串Python 将日期提取为字符串,python,pandas,dataframe,date,Python,Pandas,Dataframe,Date,我想在python中设置一个日期范围,然后创建一个新的系列/列,并将日期格式化为字符串YYYYMMDD 这就是我到目前为止所做的: start = '20200214' # YYYYMMDD end = '20200216' # YYYYMMDD dates = pd.DataFrame(pd.to_datetime(pd.date_range(start,end).date),columns = ['dates']) dates['Year'] = dates['dates'].dt.yea
YYYYMMDD
这就是我到目前为止所做的:
start = '20200214' # YYYYMMDD
end = '20200216' # YYYYMMDD
dates = pd.DataFrame(pd.to_datetime(pd.date_range(start,end).date),columns = ['dates'])
dates['Year'] = dates['dates'].dt.year
dates['Month'] = dates['dates'].dt.month
dates['Day'] = dates['dates'].dt.day
我试图将每个元素添加为字符串,dates.Year.astype(str)+dates.Month.astype(str)+……
,但我需要前导零
因此,选择第一个日期,
2020-02-14
并将其更改为20200214
。然后冲洗并重复所有其他溶液。您的溶液可以使用:
但更简单、更快的是使用:
使用
np.where
检查条件是否小于10
,并添加0或否:
dates['final'] = dates['Year'].astype(str) + np.where(dates['Month'] < 10,"0"+dates['Month'].astype(str),dates['Month'].astype(str))+ np.where(dates['Day'] < 10,"0"+dates['Day'].astype(str),dates['Day'].astype(str))
dates['final']=dates['Year'].astype(str)+np.where(dates['Month']<10,“0”+dates['Month'].astype(str),dates['Month'].astype(str))+np.where(dates['Day']<10,“0”+dates['Day'].astype(str),dates['Day'.astype(str))
输出:
dates Year Month Day reformatted_date
0 2020-02-14 2020 2 14 20200214
1 2020-02-15 2020 2 15 20200215
2 2020-02-16 2020 2 16 20200216
此外,此选项还包括:
d = datetime.datetime.now()
c = str(d)[0:10] //to string
print(c.replace('-', ''))
//data comes in this format yyyy-mm-dd hh:mm:ss
//output yyyymmdd
或者这个:
d = datetime.datetime.now()
c = d.isoformat() //to string
e = c[0:10]
print (e.replace('-', ''))
//data comes in this format yyyy-mm-dd hh:mm:ss
//output yyyymmdd
这回答了你的问题吗?你做过什么调查吗?关于这个主题有很多资源,包括上面的一个。
dates['reformatted_date'] = dates['dates'].dt.strftime('%Y%m%d')
dates Year Month Day reformatted_date
0 2020-02-14 2020 2 14 20200214
1 2020-02-15 2020 2 15 20200215
2 2020-02-16 2020 2 16 20200216
d = datetime.datetime.now()
c = str(d)[0:10] //to string
print(c.replace('-', ''))
//data comes in this format yyyy-mm-dd hh:mm:ss
//output yyyymmdd
d = datetime.datetime.now()
c = d.isoformat() //to string
e = c[0:10]
print (e.replace('-', ''))
//data comes in this format yyyy-mm-dd hh:mm:ss
//output yyyymmdd