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?
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.
Fastest way is:
import calendar
days = dict(zip(calendar.day_name, range(7)));
days['Friday']
Btw, strptime is slow and is overkill for this trivial operation.
Comparing to @Mike version
In [7]: timeit time.strptime('Friday', "%A").tm_wday
The slowest run took 337.46 times longer than the fastest. This could mean that an intermediate result is being cached
100000 loops, best of 3: 7.14 µs per loop
In [8]: timeit days['Friday']
The slowest run took 22.05 times longer than the fastest. This could mean that an intermediate result is being cached
10000000 loops, best of 3: 54.1 ns per loop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With