iqueqiorio iqueqiorio - 7 months ago 29
Python Question

Weekday as String to number

I am trying to convert my weekday as a string to an int in python here is what I have

from datetime import date, datetime, time, time delta
from pytz import timezone

now = datetime.now(timezone('UTC'))
dt_tz = now.astimezone(timezone('US/Eastern'))
dt = dt_tz.replace(tzinfo=None)
weekday = 'Friday'
weekday_as_int = dt.strptime(weekday, "%A")


But i get this error

ValueError: time data 'Friday' does not match format '%A'


Why won't it change
Friday
to a int?

Answer

The right format for a full weekday is %A:

import time
weekday_as_int = time.strptime('friday', "%A").tm_wday

>>> weekday_as_int.tm_wday
4 

Count starts with zero for Monday:

>>> time.strptime('Monday', "%A").tm_wday
0

Some timings:

@Rustem's version:

%%timeit
days = dict(zip(calendar.day_name, range(7))); 
days['Friday']
10000 loops, best of 3: 104 µs per loop

This version:

%timeit time.strptime('Friday', "%A").tm_wday
10000 loops, best of 3: 19.7 µs per loop

Looks like strptime is five times faster.

Comments