Skip to content Skip to sidebar Skip to footer

Convert Python Date Format (%Y) To Java (yyyy)

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

Solution 1:

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


Post a Comment for "Convert Python Date Format (%Y) To Java (yyyy)"