How to subtract days from a date using datetime [duplicate] - python

This question already has answers here:
How to perform arithmetic operation on a date in Python?
(2 answers)
Closed 2 years ago.
Something surely extremely simple, but I've been browsing around for almost one hour and couldn't find:
Working with Python, I have a date d="2020-01-22" (means January, 22nd, 2020) and I want to calculate the date corresponding to d - 57 days. With datetime, surely, but how, exactly?

Use the following code-
from datetime import datetime, timedelta
d = datetime.today()
new_d = d - timedelta(days=57)

Use package datetime.
# python3
import datetime
d = datetime.datetime.strptime("2020-01-22", '%Y-%m-%d')
print(d - datetime.timedelta(days=57)) # 2019-11-26 00:00:00

You can use datetime.strptime. this is the main function for parsing strings into datetimes. It can handle all type of formats, with the format determined by a format string you provide. You can read in detail here
from datetime import datetime
date_time= datetime.strptime('2020-01-22", '%Y-%m-%d')
print(date_time)

Related

The right way to parse date

Exist an easier way to do this kind of parse date?
I'm trying to make a filter in pandas to localize dates 3 months ago and loc the entire month too.
The code works, but I'm searching for the best way.
final_date = pd.to_datetime(f'{(datetime.today() - timedelta(days=90)).year}-{(datetime.today() - timedelta(days=90)).month}-01', dayfirst=True)
My Suggestion
This version of the code is more concise and easier to read.
It avoids using multiple calls to datetime.today() and string formatting.
import pandas as pd
from datetime import date, timedelta
# Calculate the date 90 days ago
d = date.today() - timedelta(days=90)
# Format the date as a string in the '%Y-%m-01' format
date_str = d.strftime('%Y-%m-01')
# Parse the string as a datetime object
final_date = pd.to_datetime(date_str, dayfirst=True)

How do I get rid of the year, month, and day? [duplicate]

This question already has answers here:
Compare only time part in datetime - Python
(3 answers)
Closed 1 year ago.
I was trying to write a program that converts a string to datetime type. The code looks like this.
import datetime
time="20:36"
p=datetime.datetime.strptime(time, "%H:%M")
print(p)
and the output was
1900-01-01 20:36:00
How do I get rid of the '1990-01-01' ?
It's unfortunate that you cannot simply write
p = datetime.time.strptime(time, "%H:%M")
because time.strptime is not defined. You are forced to use datetime.strptime, which returns a datetime object no matter what fields are actually being parsed.
On the plus side, you can get the time object you want relatively easily.
t = p.time()
print(t) # Outputs 20:36:00
You're creating a datetime object from your string and displaying the datetime as a whole.
What you should do:
display just the time part:
use strftime:
The code
import datetime
time="20:36"
p=datetime.datetime.strptime(time, "%H:%M")
print(p.strftime("%H:%M"))
use time:
The code:
import datetime
time="20:36"
p=datetime.datetime.strptime(time, "%H:%M")
print(p.time())
What you really should do:
Create a time object from your data. For that you can use datetime.time
import datetime
time="20:36"
hour, minute = time.split(":")
t = datetime.time(hour=int(hour), minute=int(minute))
print(t)

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'

Comparing date in python and applying a condition on comparison [duplicate]

This question already has answers here:
How to compare two dates?
(6 answers)
Closed 3 years ago.
i want to compare/subtract two date's due date from current date in python and apply a condition on this subtraction that if the difference is >0 days then calculate fine by multiplying difference with fine per day
from datetime import date
a=date.today()
issuedate=date(2019,5,9)
duedate#should be 5 days after issue date i can't find the method for doing this
check=a-duedate
# if check>0days:
# print(check days*40)
You need to use the timedelta function in the datetime module:
from datetime import date
import datetime
a=date.today()
issuedate=date(2019,5,9)
duedate = issuedate+datetime.timedelta(days=5)
check=a-duedate
print(check>=datetime.timedelta(days=0))
Use timedelta
from datetime import timedelta
duedate = issuedate + timedelta(days=5)
check=(a-duedate).days

Python dateutil returns YYYY-MM-DD, but I need it reversed , help please? [duplicate]

This question already has answers here:
How to print a date in a regular format?
(25 answers)
Closed 4 years ago.
I've got a piece of script in python that parses a line containing date and time:
d = dateutil.parser.parse("%s %s" % (m.group('date'),
m.group('time')), dayfirst=True)
it returns the date in YYYY-MM-DD. How can I get it to say Weekday DD Month YYYY? Or if that is not possible DD-MM-YYYY?
Additionally, it also gives the time in HH:MM:SS, but I only need HH:MM, is there a way to lose the seconds?
Thank you!
I'm a complete novice to python so hope that anyone can help me, thank you very much!
Use datetime module's strftime to change the format according to the docs.
d = '2019-01-09'
d = datetime.datetime.strptime(d, '%Y-%m-%d')
print(d)
d = d.strftime('%A %d %B %Y %H:%M') # %I:%M if you want 12 hour format
print(d) # Wednesday 09 January 2019 00:00
from datetime import date, timedelta
day = date.today() # this gives you output in default YYYY-MM-DD format
now = datetime.now() # this give your output in default YYYY-MM-DD hh:mm:ss.millisec format
timestamp = now.strftime('%d-%m-%Y-%H:%M') # this gives you the output in the format you are looking for. See the screenshot
Have a look at this link for further details: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

Categories