Created
March 17, 2018 10:34
-
-
Save kapilt/9874de8d48c7da7477969dea19bc8c58 to your computer and use it in GitHub Desktop.
datetime with pyformat
This file contains 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
import re | |
from datetime import datetime, timedelta | |
class Date(object): | |
date_increment = re.compile('\+[0-9]+[md]') | |
def __init__(self, d=None): | |
self._d = d | |
@classmethod | |
def now(cls): | |
return cls(datetime.now()) | |
@classmethod | |
def utcnow(cls): | |
return cls(datetime.utcnow()) | |
def __getattr__(self, k): | |
return getattr(self._d, k) | |
def __format__(self, fmt=None): | |
d = self._d | |
increments = self.date_increment.findall(fmt) | |
for i in increments: | |
p = {} | |
if i[-1] == 'm': | |
p['minutes'] = float(i[1:-1]) | |
if i[-1] == 'd': | |
p['days'] = float(i[1:-1]) | |
d = d + timedelta(**p) | |
fmt = self.date_increment.sub("", fmt) | |
return d.__format__(fmt) | |
if __name__ == '__main__': | |
n = Date.now() | |
print "{now:+7d%Y-%m-%d}".format(now=n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment