如何将日期时间添加到日志文件名? [英] How do you add datetime to a logfile name?

查看:73
本文介绍了如何将日期时间添加到日志文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建日志文件时,我希望名称包含日期时间.

When I create my logfile, I want the name to contain the datetime.

在Python中,您可以将当前日期时间获取为:

In Python you can get the current datetime as:

>>> 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来追加到日志文件名!我希望我的日志文件类似于:

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

是否有Python可以做些简单的事情?我将日志文件创建为:

Is there something Python can do to make this easy? I am creating the log file as:

fh = logging.FileHandler("mylogfile" + datetimecomp + ".log")

推荐答案

您需要

You need datetime.strftime(), this allows you to format the timestamp using all of the directives of C's strftime(). In your specific case:

>>> datetime.now().strftime('mylogfile_%H_%M_%d_%m_%Y.log')
'mylogfile_08_48_04_02_2012.log'

这篇关于如何将日期时间添加到日志文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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