python - datetime.datetime.strptime() 使用可变输入长度

标签 python c datetime ubuntu

datetime.datetime.strptime 似乎强制指令匹配,而不管实际使用的字符串长度如何。通过使用较短的字符串,指令将强制 datetime.datetime 对象在字符串中使用“某物”,而不管实际指令如何。

这是正确的行为,有足够的输入来填充指令

>>> datetime.datetime.strptime('20180822163014', '%Y%m%d%H%M%S')
datetime.datetime(2018, 8, 22, 16, 30, 14)

但是这个指令会改变之前的解析

>>> datetime.datetime.strptime('20180822163014', '%Y%m%d%H%M%S%f')
datetime.datetime(2018, 8, 22, 16, 30, 1, 400000)

如果输入字符串不够长,是否有任何方法可以删除最右边的指令而不是蚕食左边的指令?

我标记了 C 和 ubuntu,因为文档说

"The full set of format codes supported varies across platforms, because Python calls the platform C library’s strftime() function, and platform variations are common. To see the full set of format codes supported on your platform, consult the strftime(3) documentation."

编辑:

man ctime 将以下结构显示为输出。有趣的是,似乎不支持微秒 (%f) 精度。

struct tm {
     int tm_sec;    /* Seconds (0-60) */
     int tm_min;    /* Minutes (0-59) */
     int tm_hour;   /* Hours (0-23) */
     int tm_mday;   /* Day of the month (1-31) */
     int tm_mon;    /* Month (0-11) */
     int tm_year;   /* Year - 1900 */
     int tm_wday;   /* Day of the week (0-6, Sunday = 0) */
     int tm_yday;   /* Day in the year (0-365, 1 Jan = 0) */
     int tm_isdst;  /* Daylight saving time */
};

最佳答案

嗯,我猜你必须自己做,这似乎并不难,因为你知道模式。 像这样的东西应该能胜任

pattern = ""
if len(s) == 0: raise Exception "empty time string"
if len(s) <= 4: pattern += "%Y"
... # as many if as you need here

datetime.datetime.strptime(s, pattern)

如果你有长日期模式,写起来会很痛苦,但我怀疑 datetime 模块中已经有一些函数在做它——因为它只是与 C 的绑定(bind)。

您可以尝试做一些更通用的事情,并询问是否可以将其添加到 datetime 模块中。

关于python - datetime.datetime.strptime() 使用可变输入长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52796311/

相关文章:

python - 将 scipy.optimize.curve_fit 与权重一起使用

python - 如何使用 Asyncio 和 GUI 读取文件。

在 while 循环中比较 char

c - Mips 到 C 的翻译,两个 for 循环

python - Cython Memoryview 作为返回值

python - 我可以使用 nuitka 创建单个文件可执行文件吗?

c - 变量的含义(传递给函数)

c# - 使用 DateTime.MinValue 还是可以为 null 的 DateTime 更好?

python pandas 读取时间戳

python - 如何解决纳秒越界问题