如何以常规格式打印日期?
- 2024-12-02 08:41:00
- admin 原创
- 160
问题描述:
这是我的代码:
import datetime
today = datetime.date.today()
print(today)
这将打印:2008-11-22
这正是我想要的。
但是,我有一个列表,我将其附加到其中,然后突然一切都变得“奇怪”。代码如下:
import datetime
mylist = [datetime.date.today()]
print(mylist)
这将打印[datetime.date(2008, 11, 22)]
。我怎样才能获得像这样的简单日期2008-11-22
?
解决方案 1:
原因:日期是对象
在 Python 中,日期是对象。因此,当你操作它们时,你操作的是对象,而不是字符串或时间戳。
Python 中的任何对象都有两种字符串表示形式:
print
可以使用函数获取使用的常规表示str()
。它在大多数情况下是最常见的人类可读格式,用于简化显示。因此str(datetime.datetime(2008, 11, 22, 19, 53, 42))
为您提供'2008-11-22 19:53:42'
。用于表示对象性质(作为数据)的替代表示。可以使用
repr()
函数获取它,并且在开发或调试时可以方便地了解您正在操作哪种数据。repr(datetime.datetime(2008, 11, 22, 19, 53, 42))
为您提供'datetime.datetime(2008, 11, 22, 19, 53, 42)'
。
实际情况是,当您使用 打印日期时print
,它使用str()
,因此您可以看到一个漂亮的日期字符串。但是当您打印 时mylist
,您打印了一个对象列表,并且 Python 尝试使用 来表示数据集repr()
。
如何:你想用它做什么?
好吧,当你操作日期时,请一直使用日期对象。它们有数千种有用的方法,并且大多数 Python API 都要求日期是对象。
当您想要显示它们时,只需使用str()
。在 Python 中,好的做法是显式转换所有内容。因此,当需要打印时,使用 获取日期的字符串表示形式str(date)
。
最后一件事。当您尝试打印日期时,您打印了mylist
。如果您想打印日期,则必须打印日期对象,而不是它们的容器(列表)。
例如,您想在列表中打印所有日期:
for date in mylist :
print str(date)
请注意,在特定情况下,您甚至可以省略,str()
因为 print 会为您使用它。但这不应该成为一种习惯 :-)
实际案例,使用您的代码
import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist[0] # print the date object, not the container ;-)
2008-11-22
# It's better to always use str() because :
print "This is a new day : ", mylist[0] # will work
>>> This is a new day : 2008-11-22
print "This is a new day : " + mylist[0] # will crash
>>> cannot concatenate 'str' and 'datetime.date' objects
print "This is a new day : " + str(mylist[0])
>>> This is a new day : 2008-11-22
高级日期格式
日期有默认表示形式,但您可能希望以特定格式打印它们。在这种情况下,您可以使用该strftime()
方法获取自定义字符串表示形式。
strftime()
期望一个字符串模式来解释如何格式化日期。
例如:
print today.strftime('We are the %d, %b %Y')
>>> 'We are the 22, Nov 2008'
a 后面的所有字母"%"
代表某种格式:
%d
是日期数字(2 位数字,必要时以前导零作为前缀)%m
是月份数(2 位数字,必要时以前导零作为前缀)%b
是月份缩写(3 个字母)%B
是完整的月份名称(字母)%y
是缩写的年份(最后 2 位数字)%Y
年份数字是否完整(4 位数字)
ETC。
看看官方文档,或者麦卡琴的快速参考,你不可能全部了解。
自PEP3101以来,每个对象都可以拥有自己的格式,并由任何字符串的格式方法自动使用。对于 datetime 来说,格式与 strftime 中使用的格式相同。因此,您可以像这样执行与上述相同的操作:
print "We are the {:%d, %b %Y}".format(today)
>>> 'We are the 22, Nov 2008'
这种形式的优点是,您还可以同时转换其他对象。随着格式化字符串文字
的引入(自 Python 3.6,2016-12-23 起),这可以写成
import datetime
f"{datetime.datetime.now():%Y-%m-%d}"
>>> '2017-06-15'
本土化
如果您正确使用日期,日期可以自动适应当地语言和文化,但这有点复杂。也许可以再问一个问题(Stack Overflow) ;-)
解决方案 2:
import datetime
print datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
编辑:
根据Cees 的建议,我也开始使用时间:
import time
print time.strftime("%Y-%m-%d %H:%M")
解决方案 3:
date
、datetime
和对象time
都支持一种strftime(format)
方法,在显式格式字符串的控制下创建表示时间的字符串。
以下是格式代码及其指令和含义的列表。
%a Locale’s abbreviated weekday name.
%A Locale’s full weekday name.
%b Locale’s abbreviated month name.
%B Locale’s full month name.
%c Locale’s appropriate date and time representation.
%d Day of the month as a decimal number [01,31].
%f Microsecond as a decimal number [0,999999], zero-padded on the left
%H Hour (24-hour clock) as a decimal number [00,23].
%I Hour (12-hour clock) as a decimal number [01,12].
%j Day of the year as a decimal number [001,366].
%m Month as a decimal number [01,12].
%M Minute as a decimal number [00,59].
%p Locale’s equivalent of either AM or PM.
%S Second as a decimal number [00,61].
%U Week number of the year (Sunday as the first day of the week)
%w Weekday as a decimal number [0(Sunday),6].
%W Week number of the year (Monday as the first day of the week)
%x Locale’s appropriate date representation.
%X Locale’s appropriate time representation.
%y Year without century as a decimal number [00,99].
%Y Year with century as a decimal number.
%z UTC offset in the form +HHMM or -HHMM.
%Z Time zone name (empty string if the object is naive).
%% A literal '%' character.
这就是我们可以使用 Python 中的 datetime 和 time 模块做的事情
import time
import datetime
print "Time in seconds since the epoch: %s" %time.time()
print "Current date and time: ", datetime.datetime.now()
print "Or like this: ", datetime.datetime.now().strftime("%y-%m-%d-%H-%M")
print "Current year: ", datetime.date.today().strftime("%Y")
print "Month of year: ", datetime.date.today().strftime("%B")
print "Week number of the year: ", datetime.date.today().strftime("%W")
print "Weekday of the week: ", datetime.date.today().strftime("%w")
print "Day of year: ", datetime.date.today().strftime("%j")
print "Day of the month : ", datetime.date.today().strftime("%d")
print "Day of week: ", datetime.date.today().strftime("%A")
这将打印出如下内容:
Time in seconds since the epoch: 1349271346.46
Current date and time: 2012-10-03 15:35:46.461491
Or like this: 12-10-03-15-35
Current year: 2012
Month of year: October
Week number of the year: 40
Weekday of the week: 3
Day of year: 277
Day of the month : 03
Day of week: Wednesday
解决方案 4:
使用 date.strftime。格式化参数在文档中描述。
这个就是你想要的:
some_date.strftime('%Y-%m-%d')
这个考虑了区域设置。(这样做)
some_date.strftime('%c')
解决方案 5:
这更短一些:
>>> import time
>>> time.strftime("%Y-%m-%d %H:%M")
'2013-11-19 09:38'
解决方案 6:
# convert date time to regular format.
d_date = datetime.datetime.now()
reg_format_date = d_date.strftime("%Y-%m-%d %I:%M:%S %p")
print(reg_format_date)
# some other date formats.
reg_format_date = d_date.strftime("%d %B %Y %I:%M:%S %p")
print(reg_format_date)
reg_format_date = d_date.strftime("%Y-%m-%d %H:%M:%S")
print(reg_format_date)
输出
2016-10-06 01:21:34 PM
06 October 2016 01:21:34 PM
2016-10-06 13:21:34
解决方案 7:
甚至
from datetime import datetime, date
"{:%d.%m.%Y}".format(datetime.now())
出炉日期:'2013.12.25
或者
"{} - {:%d.%m.%Y}".format("Today", datetime.now())
发布日期:‘今日 - 2013.12.25’
"{:%A}".format(date.today())
出局:《星期三》
'{}__{:%Y.%m.%d__%H-%M}.log'.format(__name__, datetime.now())
输出:'__main____2014.06.09__16-56.log'
解决方案 8:
简单回答 -
datetime.date.today().isoformat()
解决方案 9:
在格式化的字符串文字中使用类型特定的字符串格式(自 Python 3.6,2016-12-23 起)datetime
(请参阅nk9使用str.format()
. 的回答) :
>>> import datetime
>>> f"{datetime.datetime.now():%Y-%m-%d}"
'2017-06-15'
日期/时间格式指令未记录为格式字符串语法的一部分,而是记录在date
、datetime
和time
的strftime()
文档中。这些基于 1989 C 标准,但自 Python 3.6 以来包含一些 ISO 8601 指令。
解决方案 10:
我讨厌为了方便而导入太多模块的想法。我宁愿使用可用模块(在本例中为),datetime
而不是调用新模块time
。
>>> a = datetime.datetime(2015, 04, 01, 11, 23, 22)
>>> a.strftime('%Y-%m-%d %H:%M')
'2015-04-01 11:23'
解决方案 11:
您需要将该datetime
对象转换为str
。
以下代码对我有用:
import datetime
collection = []
dateTimeString = str(datetime.date.today())
collection.append(dateTimeString)
print(collection)
如果您需要更多帮助请告诉我。
解决方案 12:
strftime()
在 Python 中,您可以使用模块中的date
、time
和datetime
类中的方法格式化日期时间datetime
。
在您的特定情况下,您正在使用date
中的类datetime
。您可以使用以下代码片段将today
变量格式化为具有以下格式的字符串yyyy-MM-dd
:
import datetime
today = datetime.date.today()
print("formatted datetime: %s" % today.strftime("%Y-%m-%d"))
下面是一个更完整的例子:
import datetime
today = datetime.date.today()
# datetime in d/m/Y H:M:S format
date_time = today.strftime("%d/%m/%Y, %H:%M:%S")
print("datetime: %s" % date_time)
# datetime in Y-m-d H:M:S format
date_time = today.strftime("%Y-%m-%d, %H:%M:%S")
print("datetime: %s" % date_time)
# format date
date = today.strftime("%d/%m/%Y")
print("date: %s" % time)
# format time
time = today.strftime("%H:%M:%S")
print("time: %s" % time)
# day
day = today.strftime("%d")
print("day: %s" % day)
# month
month = today.strftime("%m")
print("month: %s" % month)
# year
year = today.strftime("%Y")
print("year: %s" % year)
更多指令:
资料来源:
在 Python 中格式化日期时间
时间字符串
解决方案 13:
对于pandas.Timestamp,可以使用strftime()例如:
utc_now = datetime.now()
对于 isoformat:
utc_now.isoformat()
对于任何格式,例如:
utc_now.strftime("%m/%d/%Y, %H:%M:%S")
解决方案 14:
对于那些想要基于语言环境的日期并且不包括时间的人,请使用:
>>> some_date.strftime('%x')
07/11/2019
解决方案 15:
您可以执行以下操作:
mylist.append(str(today))
解决方案 16:
考虑到你要求做一些简单的事情来做你想做的事情,你可以:
import datetime
str(datetime.date.today())
解决方案 17:
因为print today
返回您想要的内容,这意味着今日对象的__str__
函数返回您正在寻找的字符串。
所以你也可以mylist.append(today.__str__())
这么做。
解决方案 18:
您可以使用easy_date来简化操作:
import date_converter
my_date = date_converter.date_to_string(today, '%Y-%m-%d')
解决方案 19:
以下是如何将日期显示为(年/月/日):
from datetime import datetime
now = datetime.now()
print '%s/%s/%s' % (now.year, now.month, now.day)
解决方案 20:
from datetime import date
def today_in_str_format():
return str(date.today())
print (today_in_str_format())
2018-06-23
如果这是你想要的,它就会打印出来:)
解决方案 21:
您可能想将其作为字符串附加?
import datetime
mylist = []
today = str(datetime.date.today())
mylist.append(today)
print(mylist)
解决方案 22:
我的回答需要简短的免责声明 - 我只学习了 Python 大约 2 周,所以我绝不是专家;因此,我的解释可能不是最好的,我可能使用了不正确的术语。无论如何,就这样吧。
我注意到在您的代码中,当您声明变量时,today = datetime.date.today()
您选择用内置函数的名称来命名变量。
当您的下一行代码mylist.append(today)
附加列表时,它会附加整个字符串datetime.date.today()
(您之前已将其设置为变量的值today
),而不仅仅是附加today()
。
一个简单的解决方案,尽管可能不是大多数程序员在使用 datetime 模块时会使用的解决方案,那就是更改变量的名称。
以下是我尝试过的:
import datetime
mylist = []
present = datetime.date.today()
mylist.append(present)
print present
并打印yyyy-mm-dd
。
解决方案 23:
我不完全理解但可以用来pandas
获取正确格式的时间:
>>> import pandas as pd
>>> pd.to_datetime('now')
Timestamp('2018-10-07 06:03:30')
>>> print(pd.to_datetime('now'))
2018-10-07 06:03:47
>>> pd.to_datetime('now').date()
datetime.date(2018, 10, 7)
>>> print(pd.to_datetime('now').date())
2018-10-07
>>>
和:
>>> l=[]
>>> l.append(pd.to_datetime('now').date())
>>> l
[datetime.date(2018, 10, 7)]
>>> map(str,l)
<map object at 0x0000005F67CCDF98>
>>> list(map(str,l))
['2018-10-07']
但它存储的字符串却很容易转换:
>>> l=list(map(str,l))
>>> list(map(pd.to_datetime,l))
[Timestamp('2018-10-07 00:00:00')]
解决方案 24:
也许最短的解决方案(完全符合您的情况)是:
mylist.append(str(AnyDate)[:10])
或更短,例如:
f'{AnyDate}'[:10]
PS:没必要today
。
解决方案 25:
您还可以使用内置format()
函数来格式化日期/日期时间。例如:
import datetime
format(datetime.date.today(), "%Y-%m-%d") # '2023-12-05'
如果您有一个用例需要可调用函数来格式化日期/日期时间的列表/序列,那么这尤其有用。例如,对于 OP 中的情况,我们可以将format
函数映射到mylist
以下内容:
mylist = [datetime.date(2008, 11, 22), datetime.datetime(2023, 12, 5, 11, 30, 5)]
list(map(format, mylist, ['%Y-%m-%d']*len(mylist))) # ['2008-11-22', '2023-12-05']
或者使用内置itertools
模块,可以写得更高效一些,如下所示:
from itertools import repeat
list(map(format, mylist, repeat('%Y-%m-%d'))) # ['2008-11-22', '2023-12-05']
另一个有用的用例是当我们想要转换 pandas 的日期时间列并将其格式化为字符串时。内置的 pandasdt.strftime
确实很慢,但应用速度format()
要快得多。
import pandas as pd
pd.Series(mylist).apply(format, args=["%Y-%m-%d"])
解决方案 26:
import datetime
import time
months = ["Unknown","January","Febuary","Marchh","April","May","June","July","August","September","October","November","December"]
datetimeWrite = (time.strftime("%d-%m-%Y "))
date = time.strftime("%d")
month= time.strftime("%m")
choices = {'01': 'Jan', '02':'Feb','03':'Mar','04':'Apr','05':'May','06': 'Jun','07':'Jul','08':'Aug','09':'Sep','10':'Oct','11':'Nov','12':'Dec'}
result = choices.get(month, 'default')
year = time.strftime("%Y")
Date = date+"-"+result+"-"+year
print Date
通过这种方式,您可以获得格式如下的日期:22-Jun-2017