How to increment an integer day by 5 days in python - python

Very new to python, please excuse the noob question:
I have a number that represents a date like :
date = 20121228
( representing December 28th, 2012)
How can I increment that date by 5 days in python so I end up with a new (correct) number representing the date like
date = 20130102
I don't want:
date = 20121233
Update: When I try and use datetime.strptime I get this error:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: type object 'datetime.datetime' has no attribute 'strptime'

Try this:
date = 20121228
from datetime import datetime, timedelta
dt = datetime.strptime(str(date), "%Y%m%d").date() + timedelta(days=5)
print datetime.strftime(dt, "%Y%m%d")

Parse it to a datetime.date() object, add 5 days, then reformat back to your number:
from datetime import datetime, timedelta
dt = datetime.strptime(str(date), '%Y%m%d').date()
dt += timedelta(days=5)
date = int(dt.strftime('%Y%m%d'))
Demonstration:
>>> from datetime import datetime, timedelta
>>> date = 20121228
>>> dt = datetime.strptime(str(date), '%Y%m%d').date()
>>> dt += timedelta(days=5)
>>> int(dt.strftime('%Y%m%d'))
20130102
For Python versions before Python 2.5, you'll need to use the time.strptime() version:
import time
from datetime import datetime, timedelta
dt = datetime(*(time.strptime(str(date), '%Y%m%d')[:6]))
dt += timedelta(days=5)
date = int(dt.strftime('%Y%m%d'))

You'll need to convert your date into a string first. Then use a timedelta object to add the days to the datetime object.
from datetime import datetime, timedelta
d = datetime.strptime(str(20121228), "%Y%m%d")
print (d + timedelta(days=5)).strftime("%Y%m%d")

Related

How to convert a date string zone oriented and hour string into datetime

I have two strings one: date='2021-12-30T23:00Z' where Z means UTC timezone and 23:00 means hour. I also have an hour string hour='3'. What I want is to convert date to datetime object and add this hour string to date as a delta. In result I would get a datetime object with hour: '2021-12-31T02:00Z' I tried function datetime.datetime.fromisoformat() with no luck.
Use strftime with their format.
from datetime import datetime, timedelta
date='2021-12-30T23:00Z'
date = datetime.strptime(date, '%Y-%m-%dT%H:%MZ')
new_date = date + timedelta(hours=3)
new_date = new_date.strftime('%Y-%m-%dT%H:%MZ')
print(new_date)
Output:
2021-12-31T02:00Z
You could do something like this:
from datetime import datetime
from datetime import timedelta
date = "2021-12-30T23:00Z"
hour = "3"
d = datetime.strptime(date, "%Y-%m-%dT%H:%M%z") + timedelta(hours=int(hour))
print(d)
output:
2021-12-31 02:00:00+00:00

How to convert a 'day/month' string to date in python and compare it with an Odoo date field?

I have a day/month string, I want to convert that string to date object and compare the last day of that month to another date
Example:
For 08/2021 (august, 2021) I want to compare the last day of that month (31-08-2021) to another date (date field),
For 02/2020 I what to compare 29-02-2020 < another_date (date field)
For 02/2021 I what to compare 28-02-2020 < another_date (date field)
You can use calendar.monthrange to find the last day in the month if you don't want to add dateutil.
import calendar
from datetime import datetime
def get_last_day_date(year_month_str):
date = datetime.strptime(year_month_str, "%m/%Y")
last_day = calendar.monthrange(date.year, date.month)[1]
return datetime(date.year, date.month, last_day)
get_last_day_date("08/2020")
# datetime.datetime(2020, 8, 31, 0, 0)
This examples shows you how to convert '02/2020' to a Python datetime and how to get the last day of that month. You can use it to compare the result to another datetime:
import datetime
from dateutil.relativedelta import relativedelta
date = '02/2020'
last_day = datetime.datetime.strptime(date, '%m/%Y') + relativedelta(day=31)
# last_day will be a datetime of the last day of the month which you can use to compare against another datetime
In this example, the result is datetime.datetime(2020, 2, 29, 0, 0) because 2020 was a leap year
b='08/2021'
a=b.split('/')
import calendar
import datetime
z=(str(calendar.monthrange(int(a[1]),int(a[0]))[1])+'-'+b.replace('/','-'))
d=datetime.datetime.strptime(z,'%d-%m-%Y').date()
print(d)
n=datetime.date.today()
print(n)
n<d
Output:
2021-08-31
2021-01-28
True
It can be done by just importing/using datetime library and here you can see how.
By passing string date into method.
import datetime
def convert_string_to_datetime(self, datetime_in_string):
datetime_in_string = str(datetime_in_string)
datetime_format = "%Y-%m-%d %H:%M:%S"
datetime_in_datetime_format = datetime.datetime.strptime(datetime_in_string, datetime_format)
return datetime_in_datetime_format
new_datetime_field = convert_string_to_datetime(datetime_in_string)
By modifying with in single line
import datetime
new_datetime_field = datetime.datetime.strptime(YOUR_DATETIME_IN_STRING, "%Y-%m-%d %H:%M:%S")
After converting into datetime now comparison is possible like.
if new_datetime_field > odoo_datetime_field:
pass

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

Get year,month and day from python variable

I'd like to get the break of a variable by year, month and day. Here's what I got:
import datetime
from datetime import date, timedelta
yesterday = date.today() - timedelta(1)
print (yesterday)
year = datetime.date.yesterday.year
month = datetime.date.yesterday.month
day=datetime.date.yesterday.day
print (year)
print (month)
print (day)
I'm getting an error that datetime.date has no attribute. I'm a total noob at python and I'm stuck, any help is appreciated
you were close
import datetime
from datetime import date, timedelta
yesterday = date.today() - timedelta(1)
print (yesterday)
year = yesterday.year
month = yesterday.month
day=yesterday.day
print (year)
print (month)
print (day)
result is
2019-03-10
2019
3
10
You can use strftime method
A simple example:
>>> from datetime import datetime
>>> now = datetime.utcnow()
>>> year_month_day_format = '%Y-%m-%d'
>>> now.strftime(year_month_day_format)
'2020-11-06'
>>> hour_minute_format = '%H:%M'
>>> now.strftime(hour_minute_format)
'22:54'
Hopping, it will help someones
You can also simplify your import statements like so:
from datetime import datetime, timedelta
yesterday = datetime.today() - timedelta(1)
print(yesterday)
year = yesterday.year
month = yesterday.month
day = yesterday.day
print(year)
print(month)
print(day)
You will get the output:
2019-03-10 21:19:36.695577
2019
3
10
For current day
import datetime
current_datetime=datetime.datetime.now()
print("current_year:{}".format(current_datetime.year))
print("current_month:{}".format(current_datetime.month))
print("current_day:{}".format(current_datetime.day))
If you want in this format for example "10-Oct-2018". You can try this code for current day.
from datetime import datetime, timezone
now_utc = datetime.now(timezone.utc)
year = now_utc.strftime("%Y")
month = now_utc.strftime("%b")
day = now_utc.strftime("%d")
result = day+"-"+month+"-"+year
print(result)

How to convert a timedelta object into a datetime object

What is the proper way to convert a timedelta object into a datetime object?
I immediately think of something like datetime(0)+deltaObj, but that's not very nice... Isn't there a toDateTime() function or something of the sort?
It doesn't make sense to convert a timedelta into a datetime, but it does make sense to pick an initial or starting datetime and add or subtract a timedelta from that.
>>> import datetime
>>> today = datetime.datetime.today()
>>> today
datetime.datetime(2010, 3, 9, 18, 25, 19, 474362)
>>> today + datetime.timedelta(days=1)
datetime.datetime(2010, 3, 10, 18, 25, 19, 474362)
Since a datetime represents a time within a single day, your timedelta should be less than 24 hours (86400 seconds), even though timedeltas are not subject to this constraint.
import datetime
seconds = 86399
td = datetime.timedelta(seconds=seconds)
print(td)
dt = datetime.datetime.strptime(str(td), "%H:%M:%S")
print(dt)
23:59:59
1900-01-01 23:59:59
If you don't want a default date and know the date of your timedelta:
date = "05/15/2020"
dt2 = datetime.datetime.strptime("{} {}".format(date, td), "%m/%d/%Y %H:%M:%S")
print(dt2)
2020-05-15 23:59:59
I found that I could take the .total_seconds() and use that to create a new time object (or datetime object if needed).
import time
import datetime
start_dt_obj = datetime.datetime.fromtimestamp(start_timestamp)
stop_dt_obj = datetime.datetime.fromtimestamp(stop_timestamp)
delta = stop_dt_obj - start_dt_obj
delta_as_time_obj = time.gmtime(delta.total_seconds())
This allows you to do something like:
print('The duration was {0}'.format(
time.strftime('%H:%M', delta_as_time_obj)
)
Improving #sadpanduar answer with example on converting one column in pandas.DataFrame:
from datetime import timedelta
import time
def seconds_to_datetime(seconds, format='%Y-%m-%d %H:%M:%S'):
td = timedelta(seconds=seconds)
time_obj = time.gmtime(td.total_seconds())
return time.strftime(format, time_obj)
df = pd.read_csv(CSV_PATH)
df['TIMESTAMP_COLUMN'] = df['TIMESTAMP_COLUMN'].apply(seconds_to_datetime)
import datetime`enter code here
lastDownloadedDate = datetime.date(2022,8,4)
print('lastDownloadedDate: ', lastDownloadedDate)
fdate = lastDownloadedDate + datetime.timedelta(days=1)
fdate = datetime.datetime.strptime(str(fdate), "%Y-%m-%d")
fdate = datetime.date(fdate.year, fdate.month, fdate.day)
print('fdate: ', dt3)`

Categories

Resources