Convert YYYY-MM-DD to DD-MMM-YYYY in Python [duplicate] - python

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)

Related

Comparing date objects in Python [duplicate]

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

Convert date string format to a datetime Python Object [duplicate]

This question already has answers here:
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 2 years ago.
i've one doubt.
I'm doing request to an API which return me event date. I was hope that date will be a timestamp, but i get this value:
{"date":"2020-08-24T21:15:00+00:00"}
I want to get a python datetime object.
How can I do that?
from datetime import datetime
dates = {"date":"2020-08-24T21:15:00+00:00"}
date = dates.get("date")
day = datetime.strptime(date, "%Y-%m-%dT%H:%M:%S+00:00")
Your looking for strptime.
Heres a good article:
https://www.programiz.com/python-programming/datetime/strptime
Use dateutil.parser which smartly parse date string:
import json
import dateutil.parser
result = '{"date":"2020-08-24T21:15:00+00:00"}'
x = json.loads(result)
dt = dateutil.parser.parse(x['date'])
# 2020-08-24 21:15:00+00:00
print(dt)
# <class 'datetime.datetime'>
print(type(dt))
I think you can do it respecting the format while parsing the string:
You have to try to follow the structure of the string and assign each value to the correct time value. For example:
str = '2018-06-29 08:15:27.243860'
time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')
Note that your case is pretty different.
It could be similar to '%Y-%m-%dT%H:%M:%S.f'

Python: Add one day to custom date? [duplicate]

This question already has answers here:
Add 1 day to my date in Python [duplicate]
(1 answer)
Adding days to a date in Python
(16 answers)
Closed 2 years ago.
I'm trying to add one day to custom date(in string). Time format is dd/mm/yyyy
Sample input:
'02/11/2020'
Output:
'03/11/2020'
from datetime import datetime, timedelta
date = '02/11/2020'
old = datetime.strptime(date, "%d/%m/%Y")
new = old + timedelta(days=1)
new_date = new.strftime("%d/%m/%Y")
print(new_date) # '03/11/2020'
You can use the datetime module
from datetime import datetime, timedelta
start = datetime.strptime("%d/%m/%Y", "02/11/2020")
end = start + datetime.timedelta(days = 1)

Converting month in number to word [duplicate]

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.

convert string to date type python [duplicate]

This question already has answers here:
Python date string to date object
(9 answers)
Closed 9 years ago.
How do I convert a string to a date object in python?
The string would be: "30-01-12" (corresponding to the format: "%d-%m-%y")
I don't want a datetime.datetime object, but rather a datetime.date
You still use datetime.datetime but then request just the .date() portion:
datetime.datetime.strptime('30-01-12', '%d-%m-%y').date()
Demonstration:
>>> import datetime
>>> datetime.datetime.strptime('30-01-12', '%d-%m-%y').date()
datetime.date(2012, 1, 30)
This should work:
import datetime
s = "30-01-12"
slist = s.split("-")
sdate = datetime.date(int(slist[2]),int(slist[0]),int(slist[1]))
from datetime import datetime,date
date_str = '30-01-12'
formatter_string = "%d-%m-%y"
datetime_object = datetime.strptime(date_str, formatter_string)
date_object = datetime_object.date()

Categories