While using Python 2.7, I wrote as follows to get a short description of the day. I am currently using 3.6. What would you recommend instead of mx.DateTime to do this?
import mx.DateTime
def func(dateVal, format):
day = ''
shortDesc = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
if format == '%d.%m.%Y':
try:
dateVal = mx.DateTime.DateTime(int(dateVal[6:10]), int(dateVal[3:5]), int(tarih[0:2]))
day = shortDesc[dateVal.day_of_week]
except:
pass
return day
CodePudding user response:
Why not use the built-in datetime
in both Python 2.7 and 3.6?
A couple of notes:
- Parse using
strptime
, rather than manually breaking up the string and converting to integer - The day_of_week almost certainly starts with 'Sun' as 0
- You can use the
strftime
date formatting character%a
for the abbreviated weekday name, although that will be the local one (rather than necessarily English) - Avoid using
except: pass
; that will hide a lot of errors that you probably do want to handle or fix or at least know about. Instead, catch specific problems and handle them appropriately (whether that'sreturn ''
or some other logic)
import datetime
def func(date, format):
the_date = datetime.datetime.strptime(date, format)
day = the_date.strftime('%a')
return day
Or, in one line:
import datetime
def func(date, format):
return datetime.datetime.strptime(date, format).strftime('%a')