-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
Copy pathdateutils.py
98 lines (79 loc) · 2.5 KB
/
dateutils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# -*- coding: utf-8 -*-
'''
Convenience functions for dealing with datetime classes
'''
from __future__ import absolute_import, division, print_function, unicode_literals
# Import Python libs
import datetime
# Import Salt libs
import salt.utils.stringutils
from salt.utils.decorators.jinja import jinja_filter
# Import 3rd-party libs
from salt.ext import six
try:
import timelib
HAS_TIMELIB = True
except ImportError:
HAS_TIMELIB = False
def date_cast(date):
'''
Casts any object into a datetime.datetime object
date
any datetime, time string representation...
'''
if date is None:
return datetime.datetime.now()
elif isinstance(date, datetime.datetime):
return date
# fuzzy date
try:
if isinstance(date, six.string_types):
try:
if HAS_TIMELIB:
# py3: yes, timelib.strtodatetime wants bytes, not str :/
return timelib.strtodatetime(
salt.utils.stringutils.to_bytes(date))
except ValueError:
pass
# not parsed yet, obviously a timestamp?
if date.isdigit():
date = int(date)
else:
date = float(date)
return datetime.datetime.fromtimestamp(date)
except Exception:
if HAS_TIMELIB:
raise ValueError('Unable to parse {0}'.format(date))
raise RuntimeError(
'Unable to parse {0}. Consider installing timelib'.format(date))
@jinja_filter('date_format')
@jinja_filter('strftime')
def strftime(date=None, format="%Y-%m-%d"):
'''
Converts date into a time-based string
date
any datetime, time string representation...
format
:ref:`strftime<http://docs.python.org/2/library/datetime.html#datetime.datetime.strftime>` format
>>> import datetime
>>> src = datetime.datetime(2002, 12, 25, 12, 00, 00, 00)
>>> strftime(src)
'2002-12-25'
>>> src = '2002/12/25'
>>> strftime(src)
'2002-12-25'
>>> src = 1040814000
>>> strftime(src)
'2002-12-25'
>>> src = '1040814000'
>>> strftime(src)
'2002-12-25'
'''
return date_cast(date).strftime(format)
def total_seconds(td):
'''
Takes a timedelta and returns the total number of seconds
represented by the object. Wrapper for the total_seconds()
method which does not exist in versions of Python < 2.7.
'''
return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6