-1

I'm looking for a method to get the day from a certain date. I have files named with the pattern "yyyymmdd.mp3" (e.g. 20190301.mp3). In my country, that day would be a Friday.

I would like to obtain the information "Friday" from the string shown above and add it to the name of the file like "friday-20190301.mp3". Is there some way to do this with Python? Thanks in advance!

Hagbard
  • 3,430
  • 5
  • 28
  • 64
agb147
  • 51
  • 5
  • 1
    Have a look at the [`datetime`](https://docs.python.org/3/library/datetime.html) module. – Graipher Mar 18 '19 at 15:18
  • Possible duplicate of [How do I get the day of week given a date in Python?](https://stackoverflow.com/questions/9847213/how-do-i-get-the-day-of-week-given-a-date-in-python) – Graipher Mar 18 '19 at 15:21
  • 1. String to datetime : https://stackoverflow.com/questions/466345/converting-string-into-datetime 2. Get the day of the week : https://stackoverflow.com/questions/9847213/how-do-i-get-the-day-of-week-given-a-date-in-python 3. Rename file : https://stackoverflow.com/questions/2491222/how-to-rename-a-file-using-python 3. Use the search bar before post... – Jeremy-F Mar 18 '19 at 15:21

3 Answers3

1

Use datetime and strftime:

from datetime import datetime

datetime_obj = datetime.strptime('20190301', '%Y%m%d')
print(datetime_obj.strftime('%A'))

Once you obtained the weekday, you can change the filename using the replace function.

ALFA
  • 1,726
  • 1
  • 10
  • 19
  • You could use [`date.strftime`](https://docs.python.org/3/library/datetime.html#datetime.date.strftime) to get the name of the weekday. – Matthias Mar 18 '19 at 15:21
  • If you must use an integer weekday, definitely use [`isoweekday()`](https://docs.python.org/3/library/datetime.html#datetime.date.isoweekday) which is the international standard. `weekday()` is c legacy. – FHTMitchell Mar 18 '19 at 15:27
  • Edited using `strftime` to get the name of the weekday. Thanks @Matthias – ALFA Mar 18 '19 at 15:30
1

Pretty similar to @ALFA's answer, but this is a full solution:

from datetime import datetime

example_filename = '20190301.mp3'

def convert(filename):
    day_of_week = datetime.strptime(filename, '%Y%m%d.mp3').strftime('%A').lower()
    return '{}_{}'.format(day_of_week, filename)

result = convert(example_filename)
# --> 'friday_20190301.mp3'
FHTMitchell
  • 11,793
  • 2
  • 35
  • 47
1
import datetime
import calendar

def new_name(val):
    my_date = datetime.datetime.strptime(val.split('.')[0], "%Y%m%d").date()
    day = calendar.day_name[my_date.weekday()] 
    return ('{}-{}'.format(day,val))


print (new_name('20190301.mp3'))

Output:

Friday-20190301.mp3

ncica
  • 7,015
  • 1
  • 15
  • 37