License New BSD license
Lines 19
Keywords
date (2) datetime (2) dateutil (1) interval (1)
Permissions
Group Owner: iCapsid
Viewable by Everyone
Editable by All Siafoo Users
Hide
Know what you're getting – Unlike many sites, all our code is clearly licensed. Join Siafoo Now or Learn More

Smart interval conversions to native datetime objects Atom Feed 0

In Brief Pass in a string, get back a native datetime object. If end_interval is True, fills in the field with the last fitting time.... more
# 's
 1from datetime import datetime, timedelta
2from dateutil.relativedelta import relativedelta
3
4def convert_interval(value, end_interval=False):
5 formats = ['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d', '%Y-%m', '%Y']
6 add_if_end = [None, relativedelta(seconds=59), relativedelta(days=1, seconds=-1),
7 relativedelta(months=1, seconds=-1), relativedelta(years=1, seconds=-1)]
8
9 for format, aie in zip(formats, add_if_end):
10 try:
11 dt = datetime.strptime(value, format)
12 if end_interval and aie:
13 dt += aie
14 return dt
15 # Note: to make timezone aware, do something like dt = my_timezone.localize(dt)
16 except ValueError:
17 pass
18
19 raise Invalid(self.message('invalidDate', state), value, state)
20

Pass in a string, get back a native datetime object. If end_interval is True, fills in the field with the last fitting time.

In other words: passing 2009-01-03 with end_interval off will create a datetime object with 2009-01-03 00:00:00. With end_interval on, will create 2009-01-03 23:59:59.

Good for specifying intervals easily (2009->2009 now means all year).