[英]How do I perform math operations on dates and sort them in Python?
I have dates in a Python script that I need to work with that are in a list. 我在列表中需要使用Python脚本中的日期。 I have to keep the format that already exists. 我必须保留已经存在的格式。 The format is YYYY-MM-DD. 格式为YYYY-MM-DD。 They are displayed in the form ['2010-05-12', '2011-04-15', 'Date', '2010-04-20', '2010-11-05'] where the order of the dates appears to be random and they are made into lists with seemingly insignificant lengths. 它们以['2010-05-12','2011-04-15','Date','2010-04-20','2010-11-05']的形式显示,其中日期的顺序出现是随机的,它们被制成长度似乎很小的列表。 The length of this data can get very large. 该数据的长度可能会非常大。 I need to know how to sort these dates into a chronological order and omit the seemingly randomly placed entries of 'Date' from this order. 我需要知道如何将这些日期按时间顺序排序,并从该顺序中忽略看似随机放置的“日期”条目。 Then I need to be able to perform math operations such as moving up and down the list. 然后,我需要能够执行数学操作,例如上下移动列表。 For example if I have five dates in order I need to be able to take one date and be able to find a date x spaces ahead or behind that date in the order. 例如,如果我有五个日期,那么我需要能够接受一个日期,并且能够找到该日期在该日期之前或之后x个空格的日期。 I'm very new to Python so simpler explanations and implementations are preferred. 我对Python还是很陌生,因此首选更简单的解释和实现。 Let me know if any clarifications are needed. 让我知道是否需要任何澄清。 Thanks. 谢谢。
You are asking several questions at the same time, so I'll answer them in order. 您同时问几个问题,所以我会按顺序回答。
To filter out the "Date"
entries, use the filter
function like this: 要过滤掉"Date"
条目,请使用如下filter
功能 :
dates = ['2011-06-18', 'Date', '2010-01-13', '1997-12-01', '2007-08-11']
dates_filtered = filter(lambda d: d != 'Date', dates)
Or perhaps like this, using Python's list comprehensions , if you find it easier to understand: 也许像这样,使用Python的列表推导 ,如果您发现它更容易理解:
dates_filtered = [d for d in dates if d != 'Date']
You might want to convert the data types of the date items in your list to the date
class to get access to some date-related methods like this: 您可能希望将列表中日期项目的数据类型转换为date
类,以访问某些与日期相关的方法,例如:
from datetime import datetime
date_objects = [datetime.strptime(x,'%Y-%m-%d').date() for x in dates_filtered]
And to sort the dates you simply use the sort
method 并对日期进行排序,您只需使用sort
方法
date_objects.sort()
The syntax in Python for accessing items and ranges of items in lists (or any "sequence type") is quite powerful. Python中用于访问列表(或任何“序列类型”)中项目和项目范围的语法非常强大。 You can read more about it here . 您可以在此处了解更多信息 。 For example, if you want to access the last two dates in your list you could do something like this: 例如,如果您想访问列表中的最后两个日期,则可以执行以下操作:
print(date_objects[-2:]
If you put it all together you'll get something like this: 如果将所有内容放在一起,将会得到以下内容:
from datetime import datetime
dates = ['2011-06-18', 'Date', '2010-01-13', '1997-12-01', '2007-08-11']
my_dates = [datetime.strptime(d, '%Y-%m-%d').date()
for d in dates
if d != 'Date']
my_dates.sort()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.