如何从python中的datetime.now()获取最小,秒和毫秒? [英] How to get min, seconds and milliseconds from datetime.now() in python?

查看:5843
本文介绍了如何从python中的datetime.now()获取最小,秒和毫秒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>>> a = str(datetime.now())
>>> a
'2012-03-22 11:16:11.343000'

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

I need to get a string like that: '16:11.34'.

应尽可能的紧凑。

或者应该使用time()吗?
如何获取?

Or should I use time() instead? How do I get it?

推荐答案

如何:

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

我不知道你的意思是毫秒只有2位数,但这应该保持为2位小数。可以通过操纵strftime格式字符串来减少精度,可能会有一个更优雅的方式 - 我不完全确定。

I'm not sure what you mean by "Milliseconds only 2 digits", but this should keep it to 2 decimal places. There may be a more elegant way by manipulating the strftime format string to cut down on the precision as well -- I'm not completely sure.

编辑

如果%f 修饰符对您无效,可以尝试以下操作: / p>

If the %f modifier doesn't work for you, you can try something like:

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

假设你只想截断精度。

这篇关于如何从python中的datetime.now()获取最小,秒和毫秒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆