如何将日期时间添加到日志文件名中?
当我创建日志文件时,我希望名称包含日期时间。
在 Python 中,您可以通过以下方式获取当前日期时间:
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2012, 2, 3, 21, 35, 9, 559000)
str 版本
>>> str(datetime.now())
'2012-02-03 21:35:22.247000'
不是一个很好的 str 附加到日志文件名!我希望我的日志文件类似于:
mylogfile_21_35_03_02_2012.log
Python 可以做些什么来使这变得简单吗?我将日志文件创建为:
fh = logging.FileHandler("mylogfile" + datetimecomp + ".log")
When I create my logfile, I want the name to contain the datetime.
In Python you can get the current datetime as:
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2012, 2, 3, 21, 35, 9, 559000)
The str version is
>>> str(datetime.now())
'2012-02-03 21:35:22.247000'
Not a very nice str to append to the logfile name! I would like my logfile to be something like:
mylogfile_21_35_03_02_2012.log
Is there something Python can do to make this easy? I am creating the log file as:
fh = logging.FileHandler("mylogfile" + datetimecomp + ".log")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您需要
datetime.strftime()
,这允许您使用 的所有指令来格式化时间戳CSstrftime()
。在您的具体情况下:You need
datetime.strftime()
, this allows you to format the timestamp using all of the directives of C'sstrftime()
. In your specific case:您还可以使用
TimedRotatingFileHandler
< /strong> 将为您每天(或您想要的任何时候)处理日期和展期。默认情况下,格式取决于翻转间隔:
但您可以按照此处所示进行修改,方法如下:
You could also use a
TimedRotatingFileHandler
that will handle the date and the rollover every day (or whenever you want) for you.By default the format will be depending on the rollover interval:
But you can modify that as showed here, by doing something like:
是的。查看日期时间 API,特别是
strftime
。Yes. Have a look at the datetime API, in particular
strftime
.使用 format() 的另一个解决方案:
我在自己的项目中使用了这个
编辑:正如我发现的 f(formatted)-strings 一样,这将是另一个解决方案:
Another Solution using format():
I used this in my own project
edit: as I found out about f(ormatted)-strings, this would be another solution:
我们可以使用 datetime.now() 来获取当前时间戳。这是我用来创建带有时间戳的日志文件的代码 -
We can use datetime.now() to get current timestamp. Here is my code that I am using to create log file with timestamp -
要打印
小时
、分钟
、日
、月
和年
,请使用以下命令语句from
datetime
importdatetime
To print
hour
,minutes
,day
,month
andyear
, use the following statementfrom
datetime
importdatetime