Created
August 17, 2015 07:29
-
-
Save damnit/660e75e3bab5bece0688 to your computer and use it in GitHub Desktop.
fun with date stuff
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from __future__ import print_function | |
| import re | |
| import datetime | |
| def parse_date(datestring, format): | |
| """ takes a string and returns the parsed date | |
| >>> parse_date('29.11.2013','%d.%m.%Y') | |
| datetime.datetime(2013, 11, 29, 0, 0) | |
| """ | |
| return datetime.datetime.strptime(datestring, format) | |
| def convert_date(datestring): | |
| """ takes a datestring formatted like '29.11.2013' | |
| and returns a datetime object | |
| >>> convert_date('29.11.2013') | |
| '2013-11-29T00:00:00Z' | |
| """ | |
| dt = parse_date(datestring, '%d.%m.%Y') | |
| return dt.isoformat() + 'Z' | |
| def parse_isotimestamp(timestamp): | |
| """ parse an iso timestamp with regex and return the seven matching groups | |
| >>> foo = '2014-12-12T21:00:00+0100' | |
| >>> parse_isotimestamp(foo) | |
| ('2014', '12', '12', '21', '00', '00', '+0100') | |
| """ | |
| iso_pat = r'([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})([0-9+-]{5})' | |
| mat = re.search(iso_pat, timestamp) | |
| if mat: | |
| return mat.groups() | |
| def get_calendar_week(date=None): | |
| """ get the actual calendar week | |
| >>> get_calendar_week(parse_date('2014-12-15', '%Y-%m-%d')) | |
| 51 | |
| """ | |
| if not date: | |
| date = datetime.datetime.now() | |
| return date.isocalendar()[1] | |
| def get_tomorrow(date=None): | |
| """ get tomorrows date. | |
| >>> get_tomorrow(parse_date('2014-12-15', '%Y-%m-%d')) | |
| datetime.datetime(2014, 12, 16, 0, 0) | |
| """ | |
| if not date: | |
| date = datetime.datetime.now() | |
| return date + datetime.timedelta(days=1) | |
| if __name__ == '__main__': | |
| import doctest | |
| doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment