sort dates in python array
sorted(timestamps, key=lambda d: map(int, d.split('-')))
Numpy sorting by increasing datetime
You can also use numpy for this. Assuming you have:
dates = numpy.array([datetime(2012,02,03,12,00,00), datetime(2012,02,03,15,00,00), datetime(2012,02,03,13,00,00)])
values = numpy.array([[1, 1], [3, 3], [2, 2]])
You can do at first:
unified = numpy.concatenate((dates.reshape(len(dates), 1), values), axis=1)
This will merge your two list, which considering what you want should be a better suited way to hold your data anyway. So now you have:
unified = array([[2012-02-03 12:00:00, 1, 1],
[2012-02-03 15:00:00, 3, 3],
[2012-02-03 13:00:00, 2, 2]], dtype=object)
Now you can do:
unified = numpy.sort(unified, axis=0)
This will sort after date. Now if you still want just the separate lists you can get them with:
unified[:, 0]
>>> array([2012-02-03 12:00:00, 2012-02-03 13:00:00, 2012-02-03 15:00:00], dtype=object)
unified[:, 1:]
>>> array([[1, 1],
[2, 2],
[3, 3]], dtype=object)
EDIT after your comment
Ok now that I fully understand what you want you can achieve that by replacing
unified = numpy.sort(unified, axis=0)
with:
unified = numpy.array(sorted(unified, key= lambda x: x[0]))
EDIT
have you tried what I just suggested? In my terminal:
unified = numpy.array([[datetime(2012,02,03,12,00,00), 4, 1],[datetime(2012,02,03,15,00,00), 5, 2],[datetime(2012,02,03,13,00,00), 2, 1]], dtype=object)
>>> unified
array([[2012-02-03 12:00:00, 4, 1],
[2012-02-03 15:00:00, 5, 2],
[2012-02-03 13:00:00, 2, 1]], dtype=object)
>>> unified = numpy.array(sorted(unified, key=lambda x: x[0]))
>>> unified
array([[2012-02-03 12:00:00, 4, 1],
[2012-02-03 13:00:00, 2, 1],
[2012-02-03 15:00:00, 5, 2]], dtype=object)
How to sort a list by datetime in python?
from datetime import datetime
list =
[
('2017/09/10 13:19:38', 'employee_id', 'enrolled'),
('2017/09/10 12:15:21', 'employee_id', 'deleted'),
('2017/09/10 21:19:34', 'employee_id', 'enrolled'),
('2017/09/10 22:42:50', 'employee_id', 'deleted'),
('2017/09/10 16:53:03', 'employee_id', 'enrolled')
]
sorted_list = sorted(list, key=lambda t: datetime.strptime(t[0], '%Y/%m/%d %H:%M:%S'))
Use the key
parameter of the sorted
function, in this case it tells the function to parse the first element of each tuple as a datetime string with the format '%Y/%m/%d %H:%M:%S'
and use that value for sorting.
How to sort an array by date in python?
I am not sure if you really tried every other solution on this website, but here's how you can do in a fool-proof way:
from datetime import datetime
lst=[['08/12/2020,gggggh,medium'],
['17/12/2020,hhhhhhh,medium'],
['09/12/2020,bbbbbb,low'],
['30/12/2020,bbbbbb,low']]
lst.sort(key = lambda x: datetime.strptime(x[0].split(',')[0], "%d/%m/%Y"))
# Your list `lst` is sorted now.
print(lst)
Outputs
[['08/12/2020,gggggh,medium'],
['09/12/2020,bbbbbb,low'],
['17/12/2020,hhhhhhh,medium'],
['30/12/2020,bbbbbb,low']]
Update: It might be helpful for you to also check this official documentation out regarding the date-time formatting that I used in the above code.
sort dates in python according to hour, day, month
import datetime
dates = [datetime.datetime.strptime(ts, "%Y-%m-%d %H:%M:%S %z") for ts in timestamps]
dates.sort()
sorteddates = [datetime.datetime.strftime(ts, "%Y-%m-%d %H:%M:%S %z") for ts in dates]
Do double confirm if the DateTime format corresponds. https://www.w3schools.com/python/python_datetime.asp
Sort python array field as date string by date
Just remove the array access in the lambda expression
key=lambda x['status_changed_at']: ...
and do
key=lambda x: ...
The array access is done later:
datetime.strptime(x['status_changed_at'] ...
For descending sorting, you also need
..., reverse=True)
Other than that, you need to rework your expression in strftime
, because you have the month first and it's locale dependent. %Y%m%d%H%M
probably sorts better.
Format in sorting an array of dates in Python 3
sales['date'] = sales['date'].dt.strftime('%Y/%d/%m')
dates = sales.date.sort_values()
dates.unique()
Out:
array(['2013/01/01', '2013/01/02', '2013/01/03', ..., '2015/31/07','2015/31/08', '2015/31/10'], dtype=object)
thank you for the comments above!
How to sort an array of objects by datetime in Python?
You can use the built-in sorted
function, along with datetime.strptime
from datetime import datetime
sortedArray = sorted(
unsortedArray,
key=lambda x: datetime.strptime(x['Created'], '%m/%d/%y %H:%M'), reverse=True
)
Python - How to sort date string in a Data Frame?
Convert the dates to timestamps first:
import pandas as pd
df["date"] = pd.to_datetime(df["date"], format="%m/%d/%y")
>>> df["date"].max()
How do I sort a list of datetime or date objects?
You're getting None
because list.sort()
it operates in-place, meaning that it doesn't return anything, but modifies the list itself. You only need to call a.sort()
without assigning it to a
again.
There is a built in function sorted()
, which returns a sorted version of the list - a = sorted(a)
will do what you want as well.
Related Topics
Passing a Function to Re.Sub in Python
Ipython Notebook Clear Cell Output in Code
Selenium Python Error: Element Could Not Be Scrolled into View
Overriding Properties in Python
Shift Elements in a Numpy Array
How to Quickly Estimate the Distance Between Two (Latitude, Longitude) Points
How to Get a List of All Indices of Repeated Elements in a Numpy Array
How to Cycle Through Line Styles in Matplotlib
Convert Pandas Datetimeindex to Unix Time
Passing Numpy Arrays to a C Function for Input and Output
Print List of Lists in Separate Lines
How to Access the Type Arguments of Typing.Generic
In Tensorflow, Differencebetween Session.Run() and Tensor.Eval()
How to Append to the End of an Empty List
How to Install Xgboost Package in Python (Windows Platform)
Tkinter: Mouse Drag a Window Without Borders, Eg. Overridedirect(1)
Is There a Multi-Dimensional Version of Arange/Linspace in Numpy