iqueqiorio iqueqiorio - 2 years ago 97
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 ='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
to a int?

Answer Source

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

Count starts with zero for Monday:

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

Some timings:

@Rustem's version:

days = dict(zip(calendar.day_name, range(7))); 
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download