【问题标题】:Extracting Dates into Strings将日期提取到字符串中
【发布时间】:2020-05-27 00:35:57
【问题描述】:

我想在 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.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。然后冲洗并重复所有其他操作。

【问题讨论】:

标签: python pandas dataframe date


【解决方案1】:

您的解决方案可以通过Series.str.zfill:

dates['Year'] = dates['dates'].dt.year
dates['Month'] = dates['dates'].dt.month
dates['Day'] = dates['dates'].dt.day
dates['dates1'] = (dates.Year.astype(str).str.zfill(2) + 
                   dates.Month.astype(str).str.zfill(2) + 
                   dates['Day'].astype(str))

但更简单更快的是使用Series.dt.strftime:

dates['dates2'] = dates['dates'].dt.strftime('%Y%m%d')

print (dates)
       dates  Year  Month  Day    dates1    dates2
0 2020-02-14  2020      2   14  20200214  20200214
1 2020-02-15  2020      2   15  20200215  20200215
2 2020-02-16  2020      2   16  20200216  20200216

【讨论】:

    【解决方案2】:
    >>> "{:02d}".format(1)
    '01'
    >>> "{:02d}".format(12)
    '12'
    

    【讨论】:

      【解决方案3】:

      使用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))
      

      【讨论】:

        【解决方案4】:
        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
        

        【讨论】:

          【解决方案5】:

          还有这个选项:

          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
          

          【讨论】:

            猜你喜欢
            • 2011-02-17
            • 1970-01-01
            • 2020-08-14
            • 2016-06-24
            • 2013-06-28
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多