Skip to content

Instantly share code, notes, and snippets.

@smolz
Forked from austind/cisco_mfg_date.py
Created October 28, 2017 00:47
Show Gist options
  • Save smolz/5db57f48d7ab1d24e55fb7245d64da01 to your computer and use it in GitHub Desktop.
Save smolz/5db57f48d7ab1d24e55fb7245d64da01 to your computer and use it in GitHub Desktop.
A PEP8-compliant module that parses a modern Cisco serial number into an approximate date of manufacture
#!/usr/bin/env python
import re
from datetime import date, timedelta
def cisco_mfg_date(serial):
"""Parses a Cisco serial number into an approximate manufacture date.
Modern Cisco serial numbers encode the device's year and week-of-year
of manufacture. Returned result therefore conveys seven days of
ambiguity.
Args:
serial (string): The serial number to be parsed into a date.
Returns:
date: A date object corresponding with the approximate date of
manufacture
"""
try:
exp = '^\s*[a-z]{3}([0-9]{2})(0?[1-9]|[1-4][0-9]|5[0-2])[a-z0-9]{4}\s*$'
m = re.match(exp, serial, re.I)
mfg_year = 1996 + int(m.group(1))
return date(mfg_year, 1, 1) \
+ timedelta(weeks=(int(m.group(2)))) \
- timedelta(days=1)
except AttributeError:
err = 'Serial number %s is not a valid Cisco serial number that ' \
'encodes the date of manufacture.'
raise ValueError(err % serial)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment