Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert python date format (%Y) to java (yyyy)

Tags:

python

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...

like image 269
David542 Avatar asked Oct 20 '25 07:10

David542


1 Answers

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

like image 195
AChampion Avatar answered Oct 22 '25 20:10

AChampion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!