Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weekday as String to number

Tags:

python

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?

like image 924
iqueqiorio Avatar asked Dec 11 '22 19:12

iqueqiorio


2 Answers

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.

like image 118
Mike Müller Avatar answered Dec 29 '22 00:12

Mike Müller


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
like image 26
Rustem Avatar answered Dec 29 '22 00:12

Rustem