0

我想输出字符串'2019-12-03'

=====

filename="20191203_volum.csv"
yyyy=filename[:4];print(yyyy)  
mm=filename[5:6];print(mm)  
dd=filename[7:8];print(dd)  
yyyymmdd=yyyy+'-'+mm+'-'+dd
print(yyyymmdd)

#I want to output the string '2019-12-03'
# '2019-12-03'

#The result of the program which does not go as expected is the following.
# '2019-2-3'

=====
我分别取出了yyyy、mm、dd。并加入。
然而,结果与预期不同。

  • mm = 12 但 2
  • dd = 03 但它变成了 3。


    我应该如何编写程序?我想让你告诉我。
4

1 回答 1

0

假设您的文件名中的日期总是before _,您可以:

  1. 将日期提取为字符串,
  2. 解析字符串以获取datetime对象,
  3. 然后按照你想要的方式格式化它。

它会如下:

from datetime import datetime

filename = '20191203_volum.csv'
parts = filename.split('_')
str_date = parts[0]

my_date = datetime.strptime(str_date, "%Y%m%d")
formatted_date = my_date.strftime('%Y-%m-%d')

print(formatted_date)
# '2019-12-03'
于 2019-05-03T23:54:55.880 回答