0

I want to output the string '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'

=====
I took out yyyy, mm, dd respectively. And joined.
However, the result was different from the expectation.

  • mm = 12 but 2
  • dd = 03 but it became 3.


    How should I write a program? I would like you to tell me.
saru999
  • 7
  • 4
  • 1
    Possible duplicate of [Understanding slice notation](https://stackoverflow.com/questions/509211/understanding-slice-notation) – manveti May 03 '19 at 23:48

1 Answers1

0

Assuming that the date in your filename is always before _, you could:

  1. extract the date as a string,
  2. parse the string to get a datetime object,
  3. then format it the way you want.

It would go as follow:

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'
boertel
  • 644
  • 4
  • 10
  • Thank you very much. The answers from the new direction, and the method I was taught have become very studied. 1, 2 went well. However, in 3 I got an error. The error is below. ValueError: time data '%Y%m%d' does not match format '20191203' – saru999 May 04 '19 at 07:57
  • It worked well if 3 was made as follows. I'm really thankful to you. – saru999 May 04 '19 at 08:35
  • datetime.strptime(str(str_date), '%Y%m%d').strftime('%Y-%m-%d') – saru999 May 04 '19 at 08:35
  • oh sorry, glad you figure it out, I mixed up everything :) also https://docs.python.org/2/library/datetime.html is always useful! – boertel May 04 '19 at 16:54
  • Thank you for telling me more information. That was a really big help. – saru999 May 04 '19 at 23:01