添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
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...

What do you want to convert? The occurences of the string '%Y' to the string 'yyyy' within a string '%Y ...'? You say you have multiple time formats. Can you give more examples? – Felix Jan 10, 2019 at 2:00 @Jab: Not OP, but I for example need this to convert my known pandas datetime formats (Python style) into PySpark datetime formats, which use java... – Thomas Aug 28, 2019 at 16:45

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

I've assumed the OP is trying to move from some python date format strings to java format strings (SimpleDataFormat()) and is looking to automate it. – AChampion Jan 10, 2019 at 2:16 @AChampion cool, thank you for the response and the suggestion of using a template over string replace. – David542 Jan 10, 2019 at 2:31 @AChampion I've the exact same problem but the other way around. I need to move from yyyy to %Y. Any ideas? – orak Apr 25, 2021 at 20:56

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.