How to get the month start date from input_date - python

I am developing an API where the user enters an input date in this format: 2019-07-29 which will be converted to date time to get '2019-07-29'. This will be used in queries against the database.
input_date = str(input_date)
input_date_formatted = "'" + datetime.strptime(input_date, '%Y-%m-%d').strftime('%Y-%m-%d') + "'"
I am trying to get the start of the month date for whichever input_date in this fashion: XXXX-XX-01. Any ideas?

If you are using it as a datetime and not a string later you can do this as follows (assuming input_date is a string):
date = datetime.strptime(input_date, '%Y-%m-%d')
first_day_of_month = date.replace(day=1)

I am assuming that you might need the actual input and the start of the month date.
By that logic the following code might just work out for you.
from datetime import datetime
input_date = '2019-07-29'
input_date = str(input_date)
input_date_formatted = "'" + datetime.strptime(input_date, '%Y-%m-%d').strftime('%Y-%m-%d') + "'"
input_date_formatted = input_date_formatted[:9]+"01'"
print(input_date_formatted)

from datetime import datetime
input_date = '2019-07-29'
input_date_object = datetime.strptime(input_date, '%Y-%m-%d')
first_date_object = input_date_object.date().replace(day=1)
print (first_date_object) # <class 'datetime.date'>
print (first_date_object.strftime('%Y-%m-%d')) # <class 'str'>
output:
2019-07-01
2019-07-01
NOTE:
Use datetime.date to get just date without hours:minutes:seconds
The function replace() is to replace specific or all the attributes
of a datetime object.
Date attributes of a datetime object that can be replaced by the
replace() function:
year
month
day

Related

extract date, month and year from string in python

I have this column where the string has date, month, year and also time information. I need to take the date, month and year only.
There is no space in the string.
The string is on this format:
date
Tuesday,August22022-03:30PMWIB
Monday,July252022-09:33PMWIB
Friday,January82022-09:33PMWIB
and I expect to get:
date
2022-08-02
2022-07-25
2022-01-08
How can I get the date, month and year only and change the format into yyyy-mm-dd in python?
thanks in advance
Use strptime from datetime library
var = "Tuesday,August22022-03:30PMWIB"
date = var.split('-')[0]
formatted_date = datetime.strptime(date, "%A,%B%d%Y")
print(formatted_date.date()) #this will get your output
Output:
2022-08-02
You can use the standard datetime library
from datetime import datetime
dates = [
"Tuesday,August22022-03:30PMWIB",
"Monday,July252022-09:33PMWIB",
"Friday,January82022-09:33PMWIB"
]
for text in dates:
text = text.split(",")[1].split("-")[0]
dt = datetime.strptime(text, '%B%d%Y')
print(dt.strftime("%Y-%m-%d"))
An alternative/shorter way would be like this (if you want the other date parts):
for text in dates:
dt = datetime.strptime(text[:-3], '%A,%B%d%Y-%I:%M%p')
print(dt.strftime("%Y-%m-%d"))
The timezone part is tricky and works only for UTC, GMT and local.
You can read more about the format codes here.
strptime() only accepts certain values for %Z:
any value in time.tzname for your machine’s locale
the hard-coded values UTC and GMT
You can convert to datetime object then get string back.
from datetime import datetime
datetime_object = datetime.strptime('Tuesday,August22022-03:30PM', '%A,%B%d%Y-%I:%M%p')
s = datetime_object.strftime("%Y-%m-%d")
print(s)
You can use the datetime library to parse the date and print it in your format. In your examples the day might not be zero padded so I added that and then parsed the date.
import datetime
date = 'Tuesday,August22022-03:30PMWIB'
date = date.split('-')[0]
if not date[-6].isnumeric():
date = date[:-5] + "0" + date[-5:]
newdate = datetime.datetime.strptime(date, '%A,%B%d%Y').strftime('%Y-%m-%d')
print(newdate)
# prints 2022-08-02

How to compare today's date and date stored in a string (without time)?

With python, How can I check if a date stored in a string has already passed?
My current code:
from datetime import date, datetime
date1 = date.today()
data2_str = '2018-06-25'
data2_obj = datetime.strptime(data2_str, '%Y-%m-%d')
print(date1<=data2_obj)
The code above gives me the following error:
TypeError: can't compare datetime.datetime to datetime.date
Note that I would not want to work with any time - just the date (this case the treated in 32287708)
Use the .date() method to get the date component like this:
from datetime import date, datetime
date1 = date.today()
date2_str = '2018-06-25'
date2 = datetime.strptime(date2_str, '%Y-%m-%d').date()
print(date1<=date2)
Output:
False

Remove time in date format in Python

I using:
s = "20200113"
final = datetime.datetime.strptime(s, '%Y%m%d')
I need convert a number in date format (2020-01-13)
but when I print final:
2020-01-13 00:00:00
Tried datetime.date(s, '%Y%m%d') but It's returns a error:
an integer is required (got type str)
Is there any command to get only date without hour?
Once you have a datetime object just use strftime
import datetime
d = datetime.datetime.now() # Some datetime object.
print(d.strftime('%Y-%m-%d'))
which gives
2020-02-20
You can use strftime to convert back in the format you need :
import datetime
s = "20200113"
temp = datetime.datetime.strptime(s, '%Y%m%d')
# 2020-01-13 00:00:00
final = temp.strftime('%Y-%m-%d')
print(final)
# 2020-01-13
Use datetime.date(year, month, day). Slice your string and convert to integers to get the year, month and day. Now it is a datetime.date object, you can use it for other things. Here, however, we use .strftime to convert it back to text in your desired format.
s = "20200113"
year = int(s[:4]) # 2020
month = int(s[4:6]) # 1
day = int(s[6:8]) # 13
>>> datetime.date(year, month, day).strftime('%Y-%m-%d')
'2020-01-13'
You can also convert directly via strings.
>>> f'{s[:4]}-{s[4:6]}-{s[6:8]}'
'2020-01-13'
You can use .date() on datetime objects to 'remove' the time.
my_time_str = str(final.date())
will give you the wanted result

Unable to subtract a day from any specific date format

I'm trying to subtract a day from this date 06-30-2019 in order to make it 06-29-2019 but can't figure out any way to achive that.
I've tried with:
import datetime
date = "06-30-2019"
date = datetime.datetime.strptime(date,'%m-%d-%Y').strftime('%m-%d-%Y')
print(date)
It surely gives me back the date I used above.
How can I subtract a day from a date in the above format?
try this
import datetime
date = "06/30/19"
date = datetime.datetime.strptime(date, "%m/%d/%y")
NewDate = date + datetime.timedelta(days=-1)
print(NewDate) # 2019-06-29 00:00:00
Your code:
date = "06-30-2019"
date = datetime.datetime.strptime(date,'%m-%d-%Y').strftime('%m-%d-%Y')
Check type of date variable.
type(date)
Out[]: str
It is in string format. To perform subtraction operation you must convert it into date format first. You can use pd.to_datetime()
# Import packages
import pandas as pd
from datetime import timedelta
# input date
date = "06-30-2019"
# Convert it into pd.to_datetime format
date = pd.to_datetime(date)
print(date)
# Substracting days
number_of_days = 1
new_date = date - timedelta(number_of_days)
print(new_date)
output:
2019-06-29 00:00:00
If you want to get rid of timestamp you can use:
str(new_date.date())
Out[]: '2019-06-29'
use timedelta
import datetime
date = datetime.datetime.strptime("06/30/19" ,"%m/%d/%y")
print( date - datetime.timedelta(days=1))

How to subtract from date given as user input?

So I'm trying to subtract one day from a users input of 2018-02-22 for example. Im a little bit stuck with line 5 - my friend who is is leaps and bounds ahead of me suggested I try this method for subtracting one day.
In my online lessons I haven't quite got to datetime yet so Im trying to ghetto it together by reading posts online but got a stuck with the error :
TypeError: descriptor 'date' of 'datetime.datetime' object needs an argument
from datetime import datetime, timedelta
date_entry = input('Enter a date in YYYY-MM-DD format')
year, month, day = map(int, date_entry.split('-'))
date1 = datetime.date()
new = date1.replace(day=date1.day-1, hour=1, minute=0, second=0, microsecond=0)
print (new)
So my aim is the get the out put 2018-02-21 if I put in 2018-02-22.
Any help would be amazing :)
First of all a timedeltais best used for the purpose of doing date arithmetcs. You import timedelta but don't use it.
day = timedelta(days=1)
newdate = input_datetime - day
Second problem is you're not initializing a date object properly. But in this case it would be better to use datetime as well as strptime to parse the datetime from the input string in a certain format.
date_entry = input('Enter a date in YYYY-MM-DD format')
input_date = datetime.strptime(date_entry, "%Y-%m-%d")
day = timedelta(days=1)
newdate = input_datetime - day
from datetime import datetime, timedelta
date_entry = input('Enter a date in YYYY-MM-DD format')
date1 = datetime.strptime(date_entry, '%Y-%m-%d')
print date1+timedelta(1)
Maybe you need something like this
from datetime import datetime, timedelta
date_entry = input('Enter a date in YYYY-MM-DD format ')
# convert date into datetime object
date1 = datetime.strptime(date_entry, "%Y-%m-%d")
new_date = date1 -timedelta(days=1) # subtract 1 day from date
# convert date into original string like format
new_date = datetime.strftime(new_date, "%Y-%m-%d")
print(new_date)
Output:
Enter a date in YYYY-MM-DD format 2017-01-01
'2016-12-31'

Categories

Resources