Par*_*ham 35 python datetime formatter
目前我正在记录东西,我正在使用我自己的格式化程序与自定义formatTime():
def formatTime(self, _record, _datefmt):
t = datetime.datetime.now()
return t.strftime('%Y-%m-%d %H:%M:%S.%f')
Run Code Online (Sandbox Code Playgroud)
我的问题是微秒%f,是六位数.无论如何吐出更少的数字,比如微秒的前三位数?
小智 60
从 Python 3.6 开始,该语言内置了此功能:
def format_time():
t = datetime.datetime.now()
s = t.isoformat(timespec='milliseconds')
return s
Run Code Online (Sandbox Code Playgroud)
ste*_*eha 47
最简单的方法是使用切片来切断微秒的最后三位数:
def format_time():
t = datetime.datetime.now()
s = t.strftime('%Y-%m-%d %H:%M:%S.%f')
return s[:-3]
Run Code Online (Sandbox Code Playgroud)
如果你想实际围绕这个数字而不仅仅是劈砍,那么这是一个更多的工作,但并不可怕:
def format_time():
t = datetime.datetime.now()
s = t.strftime('%Y-%m-%d %H:%M:%S.%f')
tail = s[-7:]
f = round(float(tail), 3)
temp = "%.3f" % f
return "%s%s" % (s[:-7], temp[1:])
Run Code Online (Sandbox Code Playgroud)
This method should always return a timestamp that looks exactly like this (with or without the timezone depending on whether the input dt object contains one):
2016-08-05T18:18:54.776+0000
It takes a datetime object as input (which you can produce with datetime.datetime.now()). To get the time zone like in my example output you'll need to import pytz and pass datetime.datetime.now(pytz.utc).
import pytz, datetime
time_format(datetime.datetime.now(pytz.utc))
def time_format(dt):
return "%s:%.3f%s" % (
dt.strftime('%Y-%m-%dT%H:%M'),
float("%.3f" % (dt.second + dt.microsecond / 1e6)),
dt.strftime('%z')
)
Run Code Online (Sandbox Code Playgroud)
我注意到上面的一些其他方法会省略尾随零,如果有一个(例如0.870变成0.87),这会导致我将这些时间戳输入的解析器出现问题。这个方法没有这个问题。
小智 5
一个适用于所有情况的简单解决方案:
def format_time():
t = datetime.datetime.now()
if t.microsecond % 1000 >= 500: # check if there will be rounding up
t = t + datetime.timedelta(milliseconds=1) # manually round up
return t.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
Run Code Online (Sandbox Code Playgroud)
基本上,您首先对日期对象本身进行手动舍入,然后您可以安全地修剪微秒。
您可以从微秒中减去当前日期时间。
d = datetime.datetime.now()
current_time = d - datetime.timedelta(microseconds=d.microsecond)
Run Code Online (Sandbox Code Playgroud)
这将2021-05-14 16:11:21.916229变成2021-05-14 16:11:21