This question already has answers here:
How do I parse an ISO 8601-formatted date?
(29 answers)
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 1 year ago.
Suppose we have the following list of date objects:
['2021-09-21T17:27:23.654Z', '2021-09-21T18:31:57.560Z', '2021-09-21T20:36:14.125Z'].
How do we find which of these dates is the earliest and which is the latest? Is there a way to convert these dates to seconds?
When I do the following:
dts_list = ['2021-09-21T17:27:23.654Z', '2021-09-21T18:31:57.560Z', '2021-09-21T20:36:14.125Z']
dts = [datetime.fromisoformat(d) for d in dts_list]
I get the following error message:
ValueError: Invalid isoformat string: '2021-09-21T18:31:57.560Z'
import datetime
dates_str = ['2021-09-21T17:27:23.654Z', '2021-09-21T18:31:57.560Z', '2021-09-21T20:36:14.125Z']
date_format = '%Y-%m-%dT%H:%M:%S.%f%z'
dates = [datetime.datetime.strptime(date, date_format) for date in dates_str]
# comparing dates
print('comparison:', dates[0] < dates[1])
# finding the min/max dates in list
print('min date is:', min(dates))
print('max date is:', max(dates))
# finding the index for min/max dates in list
print('index for min is:', dates.index(min(dates)))
print('index for max is:', dates.index(max(dates)))
# converting to seconds
timestamps = [date.timestamp() for date in dates]
print('dates in seconds:', timestamps)
This prints sorted list of python datetime objects.
from datetime.datetime import fromisoformat
times = ['2021-09-21T17:27:23.654Z', '2021-09-21T18:31:57.560Z', '2021-09-21T20:36:14.125Z']
# drop the 'Z' at the end
print(sorted([fromisoformat(time[:-1]) for time in times]))
You should start by converting them to datetime.datetime objects, like so:
from datetime import datetime
dts_list = ['2021-09-21T17:27:23.654Z', '2021-09-21T18:31:57.560Z', '2021-09-21T20:36:14.125Z']
# Does not account for time zones...
dts = [datetime.fromisoformat(d.strip('Z')) for d in dts_list]
Then, you can use the objects to compare their data:
print(dts[0].second < dts[1].second)
# True
Related
This question already has answers here:
Parse date string and change format
(10 answers)
Closed 24 days ago.
I'm trying to convert a list of dates (strings) in the format 2023-01-19 into the format 19-Jan-2023. The code I currently have does not work:
date_list = ['2023-01-19', '2023-01-07', '2022-11-29']
new_date_list = []
for date in date_list:
date_new_format = datetime.datetime(date, '%dd-%mmm-%yyyy')
new_date_list.append(date_new_format)
You have to first create a datetime object with strptime, then you can use strftime to reformat it:
from datetime import datetime
date_list = ['2023-01-19', '2023-01-07', '2022-11-29']
for date in date_list:
d = datetime.strptime(date, "%Y-%m-%d")
date_new_format = datetime.strftime(d, '%d-%b-%Y')
print(date_new_format)
This question already has answers here:
How to calculate number of days between two given dates
(15 answers)
Closed 2 years ago.
I'm trying to get the difference (in days) between today and a previous date here:
from datetime import date
today = date.today() # get today's date
print("Today's date:", today)
new_today = today.strftime("%Y, %#m, %Y") # convert it so that delta.days understands
print(new_today)
f_date = date(new_today)
l_date = date(2014, 7, 11)
delta = f_date - l_date
print(delta.days)
But I get an error:
TypeError: an integer is required (got type str)
I've read multiple threads on this, but they don't address using today's date in the calculation.
What's the best way to perform this calculation?
using datetime
import datetime
x = datetime.date.today()
y = datetime.date(2014, 7, 11)
diff = x-y
print(diff.days)
output
2392
I'm generating a list of random dates using Datetime and need to display as dd/mm/yy (eg 24 March 20 is 24/03/20). I can get this sorted with strftime, however it breaks the sort as it goes left to right so it's taking the day and sorting in that order.
It seems like overkill to get a datetime object, convert into a string for formatting, then convert that string back into a datetime object to sort.
How can I sort this list for dates correctly?
Thanking you in advance!
import random
from datetime import datetime, timedelta
user_test_date = datetime.strptime("12/12/21", '%d/%m/%y')
ledger = []
''' Create date for transaction '''
def date_gen():
date_step = random.randrange(1, 60) # Set range of 2 months
raw_date = user_test_date + timedelta(days =- date_step) # Alter days value each loop
date = raw_date.strftime('%w %b %y') #Change format of date
ledger.append(date)
ledger.sort(key=lambda item: item[0], reverse=True) #Sort list of dates
for i in range(10):
date_gen()
print(ledger)
here:
date = raw_date.strftime('%w %b %y') #Change format of date
you convert the datetime object to str. Try instead to skip this line and replace the last line in date_gen with ledger.sort()
This question already has answers here:
Parse date string and change format
(10 answers)
Closed 4 years ago.
i have string
date = "2018-09-12"
i want to get output like 2018-September-12
and i try like this
from datetime import datetime
date3 = datetime.strptime(date, '%Y-%m%B-%d')
or date3 = datetime.strptime(date, '%Y-%B-%d')
but always get time data '2018-09-12' does not match format '%Y-%m%B-%d'
Use strftime
Ex:
from datetime import datetime
date = "2018-09-12"
date3 = datetime.strptime(date, '%Y-%m-%d').strftime("%Y-%B-%d")
print(date3)
Output:
2018-September-12
strptime to convert string datetime to datetime object.
strftime to convert datetime object to required string format.
This question already has answers here:
How do I parse an ISO 8601-formatted date?
(29 answers)
Closed 5 years ago.
With the time value being:
value = '2017-08-31T02:24:29.000Z'
I try to convert it to a datetime object with:
import datetime
datetime_object = datetime.datetime.strptime(value, '%Y-%b-%d %I:%M%p')
But the command crashes with the exception:
ValueError: time data '2017-08-31T02:24:29.000Z' does not match format '%Y-%b-%d %I:%M%p'
You should be using a builtin Python's datautil module instead of date time:
import dateutil.parser
value = '2017-08-31T02:24:29.000Z'
result = dateutil.parser.parse(value)
First of all, you are missing the formatter for the microsecond.
Second of all, there is no second colon for dividing the minute and second.
Third, the %b operator is for the monthname (Jan,Feb,etc.). You want to use %m.
Final format is '%Y-%m-%dT%I:%M:%S.%fZ'.
This is your code:
datetime_object = datetime.datetime.strptime(value, '%Y-%m-%dT%I:%M:%S.%fZ')
You should get 2017-08-31 02:24:29 as the value of datetime_object.