如何根据python3中操作系统的日期和时间格式设置获取格式化的日期时间字符串?

2024-10-03 13:22:36 发布

您现在位置:Python中文网/ 问答频道 /正文

下图显示了日期的windows设置&;时间格式。我想使用此格式显示格式化日期&;使用函数strftime()生成的时间字符串。而且它应该可以在Python3.4及更高版本上运行,而不具有操作系统管理员权限。如何获取在python3的windows系统中设置的日期和时间格式?或者是否有任何等效的方法来获取格式化的datetime字符串

enter image description here

我尝试使用win32api.GetDateFormatwin32api.GetTimeFormat,但效果不好。这两种方法在Python3.4和Python3.9上的行为是不同的。在Python3.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'

在Python3.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+中的操作系统设置轻松生成格式化的日期时间字符串吗?


Tags: 方法字符串datetimewindows格式时间replacepdb