[英]Python datetime format like C# String.Format
我正在嘗試將應用程序從 C# 移植到 Python。 該應用程序允許用戶使用C# String.Format DateTime 格式選擇他們的日期時間格式。 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
我想你的“箍”意思是類似的。 請注意,有一些並發症:
(1) C# 格式可以將文字文本括在單引號中(您引用的鏈接中的示例)
(2) 它可能允許通過使用 (eg) \\
將單個字符轉義為文字
(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'
>>>
只需先運行一些替換:
replacelist = [["yyyy","%Y"], ["MM","%m"]] # Etc etc
for replacer in replacelist:
string.replace(replacer[0],replacer[1])
恐怕你不能。 strftime() 調用底層 C 庫的 strftime() 函數,該函數反過來采用 %X 形式的格式化指令。 您必須編寫幾行代碼才能進行轉換。
除了選定的答案之外,這適用於任何想要相同但在 c# 中格式從 python 轉換的人(Convert python datetime format to C# convert-able datetime format),下面是一個可以完成這項工作的擴展
public static string PythonToCSharpDateFormat(this string dateFormat)
{
string[][] changes = new string[][]
{
new string[]{"yyyy", "%Y"},new string[] {"yyy", "%Y"}, new string[]{"yy", "%y"},
new string[]{"y", "%y"}, new string[]{"MMMM", "%B"}, new string[]{"MMM", "%b"},
new string[]{"MM", "%m"}, new string[]{"M", "%m"}, new string[]{"dddd", "%A"},
new string[]{"ddd", "%a"}, new string[]{"dd", "%d"}, new string[]{"d", "%d"},
new string[]{"HH", "%H"}, new string[]{"H", "%H"}, new string[]{"hh", "%I"},
new string[]{"h", "%I"}, new string[]{"mm", "%M"}, new string[]{"m", "%M"},
new string[]{"ss", "%S"}, new string[]{"s", "%S"}, new string[]{"tt", "%p"},
new string[]{"t", "%p"}, new string[]{"zzz", "%z"}, new string[]{"zz", "%z"},
new string[]{"z", "%z"}
};
foreach (var change in changes)
{
//REPLACE PYTHON FORMAT WITH C# FORMAT
dateFormat = dateFormat.Replace(change[1], change[0]);
}
return dateFormat;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.