首页 > 解决方案 > 如何根据python3中操作系统的日期和时间格式设置获取格式化的日期时间字符串?

问题描述

下图显示了日期和时间格式的窗口设置。我想通过使用这种格式来显示格式化的日期和时间字符串 function strftime()。它应该适用于没有操作系统管理员权限的 python 3.4 及更高版本。python3中如何获取windows系统中设置的日期时间格式?或者是否有任何等效的方法来获取格式化的日期时间字符串?

在此处输入图像描述

我尝试使用win32api.GetDateFormatand win32api.GetTimeFormat,但效果不佳。这两种方法的行为在 python 3.4 和 python 3.9 上是不同的。在 python 3.9 中,以下代码在年份 >= 1970 时有效

>>> win32api.GetTimeFormat(0,0, datetime.datetime(1969,11,20,1,2,3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument
>>> win32api.GetTimeFormat(0,0, datetime.datetime(1970,11,20,1,2,3))
'5:02:03 PM'

在 python 3.4 中,上面的代码将引发一个ValueError. 但是可以通过设置时区来解决。并且GetDateFormat仅在年份 > 1600 时有效。

(Pdb) win32api.GetTimeFormat(0,0, datetime.datetime(1970,11,20,1,2,3))
*** ValueError: astimezone() cannot be applied to a naive datetime
(Pdb) win32api.GetDateFormat(0, 0,datetime.datetime(1601,10,10,1,2,3).replace(tzinfo=pytz.timezone('UTC')))
'10/10/1601'
(Pdb) win32api.GetTimeFormat(0, 0,datetime.datetime(1601,10,10,1,2,3).replace(tzinfo=pytz.timezone('UTC')))
'1:02:03 AM'
(Pdb) win32api.GetTimeFormat(0, 0,datetime.datetime(1600,10,10,1,2,3).replace(tzinfo=pytz.timezone('UTC')))
'1:02:03 AM'
(Pdb) win32api.GetDateFormat(0, 0,datetime.datetime(1600,10,10,1,2,3).replace(tzinfo=pytz.timezone('UTC')))
*** pywintypes.error: (87, 'GetDateFormat', 'The parameter is incorrect.')
(Pdb) win32api.GetDateFormat(0, 0,datetime.datetime(1601,10,10,1,2,3).replace(tzinfo=pytz.timezone('UTC')))
'10/10/1601'

有什么方法可以根据 python 3.4+ 中的操作系统设置轻松生成格式化的日期时间字符串?

标签: pythonpython-3.xdatetime

解决方案


推荐阅读