<s> import os <EOL> from datetime import datetime <EOL> from datetime import timedelta <EOL> class Datefile ( object ) : <EOL> EPOCH = datetime ( <NUM_LIT> , <NUM_LIT:1> , <NUM_LIT:1> ) <EOL> DAY_OF_WEEK = { '<STR_LIT>' : <NUM_LIT:0> , '<STR_LIT>' : <NUM_LIT:1> , '<STR_LIT>' : <NUM_LIT:2> , '<STR_LIT>' : <NUM_LIT:3> , '<STR_LIT>' : <NUM_LIT:4> , '<STR_LIT>' : <NUM_LIT:5> , '<STR_LIT>' : <NUM_LIT:6> } <EOL> def __init__ ( self , pid_dir , file_name , format = '<STR_LIT>' , timestamp = None ) : <EOL> if not os . path . exists ( pid_dir ) : <EOL> os . mkdir ( pid_dir ) <EOL> self . format = format <EOL> self . path = os . path . join ( pid_dir , file_name ) <EOL> if os . path . exists ( self . path ) and timestamp is None : <EOL> with open ( self . path ) as f : <EOL> self . timestamp = datetime . strptime ( f . read ( ) . strip ( ) , format ) <EOL> elif timestamp is None : <EOL> self . touch ( self . EPOCH ) <EOL> else : <EOL> self . touch ( timestamp ) <EOL> def is_older_than ( self , delta_spec = None ) : <EOL> now = datetime . utcnow ( ) <EOL> if '<STR_LIT>' in delta_spec and '<STR_LIT>' in delta_spec : <EOL> target_dow = self . DAY_OF_WEEK . get ( delta_spec [ '<STR_LIT>' ] . lower ( ) ) <EOL> today = now . date ( ) <EOL> target = self . next_dow ( today , target_dow ) <EOL> target = datetime ( day = target . day , month = target . month , year = target . year , hour = delta_spec [ '<STR_LIT>' ] ) <EOL> return today > self . timestamp . date ( ) and now > target <EOL> elif '<STR_LIT>' in delta_spec : <EOL> today = now . date ( ) <EOL> target = datetime ( day = today . day , month = today . month , year = today . year , hour = delta_spec [ '<STR_LIT>' ] ) <EOL> return today > self . timestamp . date ( ) and now > target <EOL> elif '<STR_LIT>' in delta_spec : <EOL> target_dow = self . DAY_OF_WEEK . get ( delta_spec [ '<STR_LIT>' ] . lower ( ) ) <EOL> today = now . date ( ) <EOL> target = self . next_dow ( today , target_dow ) <EOL> target = datetime ( day = target . day , month = target . month , year = target . year , hour = <NUM_LIT:4> ) <EOL> return today > self . timestamp . date ( ) and now > target <EOL> return self . timedelta ( delta_spec ) < now <EOL> def timedelta ( self , delta_spec = None ) : <EOL> if not delta_spec : <EOL> delta_spec = { '<STR_LIT>' : <NUM_LIT:1> } <EOL> delta = timedelta ( ** delta_spec ) <EOL> return self . timestamp + delta <EOL> def touch ( self , new_timestamp = None ) : <EOL> if new_timestamp is None : <EOL> new_timestamp = datetime . utcnow ( ) <EOL> with open ( self . path , '<STR_LIT:w>' ) as f : <EOL> f . write ( new_timestamp . strftime ( self . format ) ) <EOL> self . timestamp = new_timestamp <EOL> def next_dow ( self , d , day ) : <EOL> while d . weekday ( ) != day : <EOL> d += timedelta ( <NUM_LIT:1> ) <EOL> return d <EOL> def __str__ ( self ) : <EOL> return self . timestamp . strftime ( self . format ) </s>
