Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
My current method to do so is using a string replace, but perhaps I'll be missing some edge cases. The possible formatters I have are:
%d %b %Y %y %H %M %S %p %f %m %d %z %A
An example would be:
format.replace('%Y', 'yyyy')
And on and on...
–
–
One way would be to use the %
format as a template and then provide a mapping, e.g.:
In []:
from string import Template
mapping = {'Y': 'yyyy', 'm': 'MM', 'd': 'dd', 'H': 'HH', 'M': 'mm', 'S': 'ss'}
Template("%Y-%m-%d %H:%M:%S".replace('%', '$')).substitute(**mapping)
Out[]:
'yyyy-MM-dd HH:mm:ss'
Instead of doing str.replace()
you can change the template delimiter by subclassing Template
, e.g.:
In []:
class MyTemplate(Template):
delimiter = '%'
MyTemplate("%Y-%m-%d %H:%M:%S").substitute(**mapping)
Out[]:
'yyyy-MM-dd HH:mm:ss'
To know more about % format : https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
–
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.