I have a bunch of time formats in the following format:
"%Y-%m-%d %H:%M:%S"
Is there a quick way or a library to convert these to:
YYYY-MM-DD HH:MM:SS
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With