如何从python中的datetime.now()获取min,seconds和毫秒?

Pro*_*tak 17 python time datetime

>>> a = str(datetime.now())
>>> a
'2012-03-22 11:16:11.343000'
Run Code Online (Sandbox Code Playgroud)

我需要得到一个这样的字符串:'16:11.34'.

应该尽可能紧凑.

或者我应该使用time()代替?我怎么得到它?

mgi*_*son 30

关于什么:

datetime.now().strftime('%M:%S.%f')[:-4]

我不确定你的意思是"毫秒只有2位数",但这应该保持在2位小数.通过操纵strftime格式字符串可以有更优雅的方式来降低精度 - 我不完全确定.

编辑

如果%f修饰符不适合您,您可以尝试以下方法:

now=datetime.now()
string_i_want=('%02d:%02d.%d'%(now.minute,now.second,now.microsecond))[:-4]
Run Code Online (Sandbox Code Playgroud)

再说一遍,我假设你只想截断精度.

  • 什么是不正确的?它会引发错误吗?我认为%f修饰符是在python 2.6中添加的(虽然我不是肯定的) - 你使用的是什么版本的python? (2认同)

Pyt*_*nia 6

这个解决方案非常类似于@ gdw2提供的解决方案,只是正确地完成了字符串格式化以匹配您所要求的 - "应该尽可能紧凑"

>>> import datetime
>>> a = datetime.datetime.now()
>>> "%s:%s.%s" % (a.minute, a.second, str(a.microsecond)[:2])
'31:45.57'
Run Code Online (Sandbox Code Playgroud)


小智 5

如果你想要datetime.now()精确到分钟,你可以使用

datetime.strptime(datetime.now().strftime('%Y-%m-%d %H:%M'), '%Y-%m-%d %H:%M')
Run Code Online (Sandbox Code Playgroud)

类似地,小时将是

datetime.strptime(datetime.now().strftime('%Y-%m-%d %H'), '%Y-%m-%d %H')
Run Code Online (Sandbox Code Playgroud)

这有点像黑客,如果有人有更好的解决方案,我全神贯注