gpt4 book ai didi

c# - Python 日期时间格式,如 C# String.Format

转载 作者:太空宇宙 更新时间:2023-11-03 20:38:14 25 4
gpt4 key购买 nike

我正在尝试将应用程序从 C# 移植到 Python。该应用程序允许用户使用 C# String.Format DateTime formatting 选择他们的日期时间格式。 . Python 的日期时间格式甚至都不尽相同,因此我不得不跳过我的代码。

Python 有什么方法可以解析像 yyyy-MM-dd HH-mm-ss 而不是 %Y-%m-%d %H-%M-%S 这样的字符串?

最佳答案

通过使用简单的替换来转换格式字符串,您可以得到一个公平的距离。

_format_changes = (
('MMMM', '%B'),
('MMM', '%b'), # note: the order in this list is critical
('MM', '%m'),
('M', '%m'), # note: no exact equivalent
# etc etc
)

def conv_format(s):
for c, p in _format_changes:
# s.replace(c, p) #### typo/braino
s = s.replace(c, p)
return s

我猜你的“hoops”意思类似。注意有并发症:
(1) C# 格式可以用单引号括起文字文本(您引用的链接中的示例)
(2) 它可能允许通过使用(例如)\
将其转义来使单个字符成为文字(3) 12 或 24 小时制可能需要额外的工作(我没有深入研究 C# 规范;此评论基于我参与过的另一个类似练习)。
您最终可以编写一个编译器和一个字节码解释器来解决所有问题(例如 M、F、FF、FFF 等)。

另一种方法是使用 ctypes 或类似的东西直接调用 C# RTL。

更新 原始代码过于简单,并且有错别字/脑洞。下面的新代码展示了如何解决一些问题(例如文字文本,并确保输入中的文字 % 不会使 strftime 不愉快)。它不会尝试在没有直接转换(M、F 等)的情况下给出准确的答案。可能会引发异常的地方已注明,但代码在自由放任的基础上运行。

_format_changes = (
('yyyy', '%Y'), ('yyy', '%Y'), ('yy', '%y'),('y', '%y'),
('MMMM', '%B'), ('MMM', '%b'), ('MM', '%m'),('M', '%m'),
('dddd', '%A'), ('ddd', '%a'), ('dd', '%d'),('d', '%d'),
('HH', '%H'), ('H', '%H'), ('hh', '%I'), ('h', '%I'),
('mm', '%M'), ('m', '%M'),
('ss', '%S'), ('s', '%S'),
('tt', '%p'), ('t', '%p'),
('zzz', '%z'), ('zz', '%z'), ('z', '%z'),
)

def cnv_csharp_date_fmt(in_fmt):
ofmt = ""
fmt = in_fmt
while fmt:
if fmt[0] == "'":
# literal text enclosed in ''
apos = fmt.find("'", 1)
if apos == -1:
# Input format is broken.
apos = len(fmt)
ofmt += fmt[1:apos].replace("%", "%%")
fmt = fmt[apos+1:]
elif fmt[0] == "\\":
# One escaped literal character.
# Note graceful behaviour when \ is the last character.
ofmt += fmt[1:2].replace("%", "%%")
fmt = fmt[2:]
else:
# This loop could be done with a regex "(yyyy)|(yyy)|etc".
for intok, outtok in _format_changes:
if fmt.startswith(intok):
ofmt += outtok
fmt = fmt[len(intok):]
break
else:
# Hmmmm, what does C# do here?
# What do *you* want to do here?
# I'll just emit one character as literal text
# and carry on. Alternative: raise an exception.
ofmt += fmt[0].replace("%", "%%")
fmt = fmt[1:]
return ofmt

测试到以下程度:

>>> from cnv_csharp_date_fmt import cnv_csharp_date_fmt as cv
>>> cv("yyyy-MM-dd hh:mm:ss")
'%Y-%m-%d %I:%M:%S'
>>> cv("3pcts %%% yyyy-MM-dd hh:mm:ss")
'3pc%p%S %%%%%% %Y-%m-%d %I:%M:%S'
>>> cv("'3pcts' %%% yyyy-MM-dd hh:mm:ss")
'3pcts %%%%%% %Y-%m-%d %I:%M:%S'
>>> cv(r"3pc\t\s %%% yyyy-MM-dd hh:mm:ss")
'3pcts %%%%%% %Y-%m-%d %I:%M:%S'
>>>

关于c# - Python 日期时间格式,如 C# String.Format,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4188032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com