1

Given this date format which i cannot change:

20201216133326

First 4 digits reprezent the year, the 5 and the 6 the month, the 7 and the 8th the day, the rest are redundant, which I don't want, is there a way to get an output as a string like :

'Year: 2020, Month: December, Day: 16 (Wednesday)'

Python 3.9

Rolfsky
  • 63
  • 7

2 Answers2

2

No need to parse strings yourself, the datetime module has all the necessary functionality:

from datetime import datetime

d = datetime.strptime('20201216133326', '%Y%m%d%H%M%S')
print(d.strftime('Year: %Y, Month: %B, Day: %d (%A)'))

Output:

Year: 2020, Month: December, Day: 16 (Wednesday)

The exact format code for strptime depends on whether your numbers are zero-padded. I also assumed that the day is followed by hours, minutes and seconds (which are not printed here).

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Jussi Nurminen
  • 2,257
  • 1
  • 9
  • 16
1

You can do this. You can use string slicing and datetime module. and also lists!

import datetime
date = "20201216133326"
year = int(date[0:4])
month = int(date[4:6])
day = int(date[6:8])
mlist = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
t = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
r = datetime.datetime.today().weekday()
print(f'Year: {year}, Month: {mlist[month-1]}, day: {day} ({t[r]})')
ppwater
  • 2,315
  • 4
  • 15
  • 29
  • If using `datetime`, why not use it to parse the date instead of doing it manually? Also why do you use `r = datetime.datetime.today().weekday()`? It should be the weekday of the date, not today... – Tomerikoo Dec 17 '20 at 11:39
  • Yeah, Jussi Nurminen's answer should be accepted... – ppwater Dec 17 '20 at 12:12