Software, technology, sysadmin war stories, and more. Feed
Wednesday, November 9, 2011

More crazy code which is in production somewhere

From the "don't do this" department (this is Python)...

# compute 4 months ago
t = time.localtime()
mnth = t[1] - 3
year = t[0]
day = 1
if mnth < 1:
  year -= 1  # adjust year
  mnth += 13  # fixup month
mnth = mnth % 12
def_date = "%04d/%02d/%02d%" % (year, mnth, day)

I've heard the old chestnut about "so and so can write (language) in any language", and it's true. It basically means some people have an internal representation of a programming language and use it no matter what environment they may be in. Maybe they write FORTRAN in C by doing crazy #define hacks so they can keep their ".gt." and ".lt".

What I can't figure out here is what the author's internal language for this particular snippet must be like. I'm torn between C and 8-bit Commodore BASIC, and this is coming from someone who used both for a very long time.

I mean, I'm not a fan of Python, and I don't use it unless I have to, and I try to avoid having it pollute my brain, but I was still able to turn up this in less than 5 minutes of searching the web:

>>> datetime.datetime.now() - datetime.timedelta(days = -120)
datetime.datetime(2012, 3, 8, 18, 36, 27, 348204)

And, yeah, 4 months vs. approximately 4 months worth of days, and all of that, I know. The thing is, the original code gives no indication why it wants "same day of whatever month was 4 months ago" instead of 120 days, or 16 weeks, or ..., so you have no idea what is really needed.

All I know is, if you're wrangling dates in a language which has a ton of libraries for this kind of stuff and you need to deal with "month 13" or "month -1", you're in trouble.