如何将日期时间添加到日志文件名中?

发布于 2025-01-02 03:01:19 字数 539 浏览 2 评论 0原文

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

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

琴流音 2025-01-09 03:01:19

您需要 datetime.strftime() ,这允许您使用 的所有指令来格式化时间戳CS strftime()。在您的具体情况下:

>>> datetime.now().strftime('mylogfile_%H_%M_%d_%m_%Y.log')
'mylogfile_08_48_04_02_2012.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'
俏︾媚 2025-01-09 03:01:19

您还可以使用 TimedRotatingFileHandler< /strong> 将为您每天(或您想要的任何时候)处理日期和展期。

from logging.handlers import TimedRotatingFileHandler
fh = TimedRotatingFileHandler('mylogfile',  when='midnight')

默认情况下,格式取决于翻转间隔:

系统将通过在文件名后附加扩展名来保存旧日志文件。扩展基于日期和时间,使用 strftime 格式 %Y-%m-%d_%H-%M-%S 或其前导部分,具体取决于翻转间隔。< /p>

但您可以按照此处所示进行修改,方法如下:

from logging.handlers import TimedRotatingFileHandler
fh = TimedRotatingFileHandler('mylogfile',  when='midnight')
fh.suffix = '%Y_%m_%d.log'

You could also use a TimedRotatingFileHandler that will handle the date and the rollover every day (or whenever you want) for you.

from logging.handlers import TimedRotatingFileHandler
fh = TimedRotatingFileHandler('mylogfile',  when='midnight')

By default the format will be depending on the rollover interval:

The system will save old log files by appending extensions to the filename. The extensions are date-and-time based, using the strftime format %Y-%m-%d_%H-%M-%S or a leading portion thereof, depending on the rollover interval.

But you can modify that as showed here, by doing something like:

from logging.handlers import TimedRotatingFileHandler
fh = TimedRotatingFileHandler('mylogfile',  when='midnight')
fh.suffix = '%Y_%m_%d.log'
凉薄对峙 2025-01-09 03:01:19

是的。查看日期时间 API,特别是 strftime

from datetime import datetime
print datetime.now().strftime("%d_%m_%Y")

Yes. Have a look at the datetime API, in particular strftime.

from datetime import datetime
print datetime.now().strftime("%d_%m_%Y")
留一抹残留的笑 2025-01-09 03:01:19

使用 format() 的另一个解决方案:

#generates a date for a generic filename
import datetime
date_raw = datetime.datetime.now()
date_processed = "{}-{}-{}_{}-{}-{}".format(date_raw.year, date_raw.month, 
                  date_raw.day, date_raw.hour, date_raw.minute, date_raw.second)
#example value: date_processed = 2020-1-7_17-17-48

我在自己的项目中使用了这个
编辑:正如我发现的 f(formatted)-strings 一样,这将是另一个解决方案:

date_processed = f"{date_raw.year}-{date_raw.month}-{date_raw.day}_{date_raw.hour}-{date_raw.minute}-{date_raw.second}"

Another Solution using format():

#generates a date for a generic filename
import datetime
date_raw = datetime.datetime.now()
date_processed = "{}-{}-{}_{}-{}-{}".format(date_raw.year, date_raw.month, 
                  date_raw.day, date_raw.hour, date_raw.minute, date_raw.second)
#example value: date_processed = 2020-1-7_17-17-48

I used this in my own project
edit: as I found out about f(ormatted)-strings, this would be another solution:

date_processed = f"{date_raw.year}-{date_raw.month}-{date_raw.day}_{date_raw.hour}-{date_raw.minute}-{date_raw.second}"
哆兒滾 2025-01-09 03:01:19

我们可以使用 datetime.now() 来获取当前时间戳。这是我用来创建带有时间戳的日志文件的代码 -

import logging
from datetime import datetime
LOG_FILENAME = datetime.now().strftime('D:/log/logfile_%H_%M_%S_%d_%m_%Y.log')
for handler in logging.root.handlers[:]:
      logging.root.removeHandler(handler)
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)    
logging.info('Forecastiong Job Started...')
logging.debug('abc method started...')

We can use datetime.now() to get current timestamp. Here is my code that I am using to create log file with timestamp -

import logging
from datetime import datetime
LOG_FILENAME = datetime.now().strftime('D:/log/logfile_%H_%M_%S_%d_%m_%Y.log')
for handler in logging.root.handlers[:]:
      logging.root.removeHandler(handler)
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)    
logging.info('Forecastiong Job Started...')
logging.debug('abc method started...')
权谋诡计 2025-01-09 03:01:19
from time import strftime

fh = logging.FileHandler(strftime("mylogfile_%H_%M_%m_%d_%Y.log"))
from time import strftime

fh = logging.FileHandler(strftime("mylogfile_%H_%M_%m_%d_%Y.log"))
醉态萌生 2025-01-09 03:01:19

要打印小时分钟,请使用以下命令语句

from datetime import datetime

print datetime.now().strftime("%H_%M_%d_%m_%Y")

To print hour, minutes, day, month and year, use the following statement

from datetime import datetime

print datetime.now().strftime("%H_%M_%d_%m_%Y")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文