python:datetime strftime无法正常工作

时间:2022-05-13 11:26:21

I am trying to print a date time into a file in a particular format due to which I have formatting a datetime object using strftime function as below:

我正在尝试将日期时间打印到特定格式的文件中,因为我使用strftime函数格式化了datetime对象,如下所示:

hFile = open("Test.csv", 'w')
for str in datelist:
   splitStr = str.split("_")
   dateTime = datetime.datetime(int(splitStr[0]), int(splitStr[1]), int(splitStr[2]), int(splitStr[3]), int(splitStr[4]), int(splitStr[6]))
   hFile.write(dateTime.strftime('%H:%M %d/%m/%Y'))

This for some of the cases works well and prints it in correct format but for some cases it prints it in the following format:

对于某些情况,这种情况很好并以正确的格式打印,但在某些情况下,它会按以下格式打印:

>1/4/2013 12:45

instead of

>12:45 1/04/2013

But when I only do:

但是当我这样做时:

>dateTime.strftime('%H %d/%m/%Y')

It doesn't switch the time and date in certain cases and prints it in correct format for all the cases. Any idea why is it happening?

在某些情况下,它不会切换时间和日期,并以正确的格式打印所有情况。知道为什么会这样吗?

An Important observartion: Everything works fine when I remove the :. So, the below command works fine. Now that makes me more confused.

一个重要的观察:当我删除以下内容时,一切正常:。所以,下面的命令工作正常。现在这让我更加困惑。

>dateTime.strftime('%H %M %d/%m/%Y')

works perfectly fine. Any idea what is the issue with putting : in the strftime?

工作得非常好。任何想法的问题是什么:在strftime?

Thanks.

1 个解决方案

#1


0  

I created an equivalent sample which seems to work.

我创建了一个似乎有效的等效样本。

from datetime import datetime
a = datetime.datetime.now()
a.strftime('%H:%M %d/%m/%Y')

>>> '11:04 22/04/2015'

#1


0  

I created an equivalent sample which seems to work.

我创建了一个似乎有效的等效样本。

from datetime import datetime
a = datetime.datetime.now()
a.strftime('%H:%M %d/%m/%Y')

>>> '11:04 22/04/2015'