5

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?

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
iqueqiorio
  • 1,149
  • 2
  • 35
  • 78

2 Answers2

13

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.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161
2

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
Rustem
  • 2,884
  • 1
  • 17
  • 32
  • @Mike, I'd say you version cannot be faster. parsing is always slower than picking by key in dictionary. Two things you doing wrong in your measure. 1. days variable supposed to be calculated once. 2. As far as strptime is slow, python tries cache the results - to help you provide better results - btw, it's not good. If you check my update, you will see that my version is faster – Rustem Dec 11 '15 at 05:51
  • How about measuring `dict(zip(calendar.day_name, range(7)))` too? – Mike Müller Dec 11 '15 at 06:01
  • @Mike, same as multipling your results to 337.46. As I said it was cached. My way is standard - build mapping first, get results after - reuse if needed. – Rustem Dec 11 '15 at 06:02
  • Agree. Your solution is better for reuse. I was looking for one-time thing. My solution is better if the date string contains more text, though. Often the questions are out of context and people want to do more than shown. – Mike Müller Dec 11 '15 at 06:43
  • > "My solution is better if the date string contains more text, though" - yes, I'm agree. – Rustem Dec 11 '15 at 06:57
  • Agree on you agreeing. ;) – Mike Müller Dec 11 '15 at 06:59