这是我的代码:
import datetime
today = datetime.date.today()
print(today)
这将打印: 2008-11-22
这正是我想要的。
但是,我有一个要附加的列表,然后突然间一切都变得“古怪”。这是代码:
import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print(mylist)
这将打印以下内容:
[datetime.date(2008, 11, 22)]
我怎样才能得到像 2008-11-22
这样的简单日期?
str()
(对列表的每个元素),因为这正是 print
对您的单独 today
对象隐式执行的操作。
为什么:日期是对象
在 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()
来表示数据集。
The How:你想用它做什么?
好吧,当您操作日期时,请一直使用日期对象。他们获得了数千种有用的方法,并且大多数 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'
"%"
之后的所有字母都代表某种格式:
%d 是天数(2 位数字,必要时以前导零为前缀)
%m 是月份编号(2 位数字,必要时以前导零为前缀)
%b 是月份的缩写(3 个字母)
%B 是完整的月份名称(字母)
%y 是年份数字的缩写(最后 2 位数字)
%Y 是完整的年份编号(4 位)
等等
Have a look at the official documentation 或 McCutchen's quick reference 你不可能全部都知道。
从 PEP3101 开始,每个对象都可以有自己的格式,任何字符串的方法格式都会自动使用它。对于日期时间,格式与 strftime 中使用的格式相同。所以你可以像上面一样做:
print "We are the {:%d, %b %Y}".format(today)
>>> 'We are the 22, Nov 2008'
这种形式的好处是你还可以同时转换其他对象。
随着 Formatted string literals 的引入(自 Python 3.6,2016-12-23),这可以写成
import datetime
f"{datetime.datetime.now():%Y-%m-%d}"
>>> '2017-06-15'
本土化
如果您以正确的方式使用日期,日期可以自动适应当地的语言和文化,但这有点复杂。也许关于SO(堆栈溢出)的另一个问题;-)
import datetime
print datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
编辑:
在 Cees' suggestion 之后,我也开始使用时间:
import time
print time.strftime("%Y-%m-%d %H:%M")
datetime import datetime
,然后是 print datetime().now().strftime("%Y-%m-%d %H:%M")
。只是语法不同。
from datetime import date; date.today().strftime("%Y-%m-%d")
对我来说仍然看起来很奇怪,但没有 import time
这是最好的。我认为 datetime 模块用于日期数学。
from datetime import datetime as dt
,现在我们可以和dt.now()
一起玩了
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
使用 date.strftime。格式参数是 described in the documentation。
这就是你想要的:
some_date.strftime('%Y-%m-%d')
这个考虑了语言环境。 (做这个)
some_date.strftime('%c')
这更短:
>>> import time
>>> time.strftime("%Y-%m-%d %H:%M")
'2013-11-19 09:38'
# 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
甚至
from datetime import datetime, date
"{:%d.%m.%Y}".format(datetime.now())
出:'25.12.2013
或者
"{} - {:%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'
简单的回答——
datetime.date.today().isoformat()
在 Formatted string literal 中使用特定类型的 datetime
字符串格式(请参阅使用 str.format()
的 nk9's answer。)(自 Python 3.6,2016-12-23 起):
>>> import datetime
>>> f"{datetime.datetime.now():%Y-%m-%d}"
'2017-06-15'
日期/时间格式指令未记录为 Format String Syntax 的一部分,而是记录在 date
、datetime
和 time
的 strftime()
文档中。它们基于 1989 C 标准,但包括自 Python 3.6 以来的一些 ISO 8601 指令。
f"{datetime.datetime.now().astimezone():%Y-%m-%dT%H:%M:%S.%f}"[:-3]+f"{datetime.datetime.now().astimezone():%z}"
也包括毫秒和时区
我讨厌为了方便而导入太多模块的想法。我宁愿使用在这种情况下为 datetime
的可用模块,而不是调用新模块 time
。
>>> a = datetime.datetime(2015, 04, 01, 11, 23, 22)
>>> a.strftime('%Y-%m-%d %H:%M')
'2015-04-01 11:23'
a = datetime.datetime(2015, 04, 01, 23, 22).strftime('%Y-%m-%d %H:%M)
在一行代码中执行此操作会更有效
您需要将 datetime
对象转换为 str
。
以下代码对我有用:
import datetime
collection = []
dateTimeString = str(datetime.date.today())
collection.append(dateTimeString)
print(collection)
如果您需要更多帮助,请告诉我。
你可以做:
mylist.append(str(today))
考虑到您要求做一些简单的事情来做您想做的事情,您可以:
import datetime
str(datetime.date.today())
对于那些想要基于区域设置的日期而不包括时间的人,请使用:
>>> some_date.strftime('%x')
07/11/2019
由于 print today
返回您想要的,这意味着今天对象的 __str__
函数返回您正在查找的字符串。
所以你也可以做mylist.append(today.__str__())
。
from datetime import date
def today_in_str_format():
return str(date.today())
print (today_in_str_format())
如果这是您想要的,这将打印 2018-06-23
:)
您可能想将其附加为字符串?
import datetime
mylist = []
today = str(datetime.date.today())
mylist.append(today)
print(mylist)
在 Python 中,您可以使用 datetime
模块中 date
、time
和 datetime
类的 strftime()
方法格式化日期时间。
在您的具体情况下,您使用的是 datetime
中的 date
类。您可以使用以下代码段将 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)
更多指令:
https://i.stack.imgur.com/bOPCe.jpg
资料来源:
在 Python 中格式化日期时间
时间
您可以使用 easy_date 来简化:
import date_converter
my_date = date_converter.date_to_string(today, '%Y-%m-%d')
我的答案的快速免责声明 - 我只学习 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
。
以下是将日期显示为(年/月/日)的方法:
from datetime import datetime
now = datetime.now()
print '%s/%s/%s' % (now.year, now.month, now.day)
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
%b
,您将获得前三个月的单词,而使用 %B
,您将获得整个月。示例:datetime.datetime.now().strftime("%Y-%b-%d %H:%M:%S")
将返回 '2018-Oct-04 09:44:08'
我不完全理解,但可以使用 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')]
对于 pandas.Timestamp,可以使用 strftime(),例如:
utc_now = datetime.now()
对于等格式:
utc_now.isoformat()
For any format 例如:
utc_now.strftime("%m/%d/%Y, %H:%M:%S")
inspect.isclass
以确保)。人们倾向于对内置函数说“类型”,对其余的说“类”,但这并不重要