Linux 如何在python中获取格式化的日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6017570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 04:06:21  来源:igfitidea点击:

How to get formatted date time in python

pythonlinux

提问by Mahakaal

I want my Linux Filename like this

我想要这样的 Linux 文件名

May-01-0340AM-2011.tar

How can i get the date variable formatted like above in Python

如何在 Python 中获取上述格式的日期变量

IN bash i write

在 bash 我写

date1=$(date +"%b-%d-%I%M%p-%G")

采纳答案by Mark Longair

You can use the same formatting string in strftimeon a datetime object:

您可以使用相同的格式化字符串strftime一对DateTime对象

>>> import datetime
>>> datetime.datetime.now().strftime('%b-%d-%I%M%p-%G')
'May-16-0245PM-2011'

Incidentally, I'd just like to put a word in for the joy of ISO-8601 date formatting:)

顺便说一句,我只想说一句ISO-8601 日期格式的乐趣:)

回答by Johnsyweb

Same formatting, using strftime():

相同的格式,使用strftime()

>>> import datetime
>>> datetime.datetime.now().strftime('%b-%d-%I%M%p-%G')
'May-16-1050PM-2011'

To get your filename, it's as simple as:

要获取您的文件名,它很简单:

 >>> datetime.datetime.now().strftime('%b-%d-%I%M%p-%G') + '.tar'
'May-16-1050PM-2011.tar'