I am trying to solve a problem. where I am defining date and time as string in below mentioned format.
date1 = '2016-12-1'
time1 = '10:30 AM'
time2 = '11:30 PM'
I have another string add_time = '01:50' type of variables is string.
what I'm looking for is:
new_date_and_time = time1 + add_time
so that it returns
date1 and new_date_and_time
> 2016-12-1, 12:20 PM (10:30 AM + 1:50)
but if I am adding time2 + add_time the date is also changed,
so it should print 2016-12-2, 1:20 AM
Is there any package which can do this?
Convert strings to datetime object, then add time using timedelta
from datetime import datetime, timedelta
date1 = '2016-12-1'
time1 = '10:30 AM'
date_object = datetime.strptime(date1 + ' ' + time1, '%Y-%m-%d %I:%M %p')
new_date_object = date_object + timedelta(hours=1) + timedelta(minutes=50)
Related
I'm trying to convert it in a simple way using str() but it doesn't work. How can I do that?
import json
import datetime
def lambda_handler(event, context):
lastUpdate="2020-09-17 03:59:21+00:00"
now = datetime.datetime.now().replace(tzinfo=datetime.timezone.utc)
diff = now - lastUpdate
print("Now:" + str(now) + lastUpdate)
Output:
errorMessage": "unsupported operand type(s) for -: 'datetime.datetime' and 'str'",
get the utc timezone and string format as below:
from datetime import datetime, timezone
lastUpdate="2020-09-17 03:59:21+00:00"
now2 = datetime.now(timezone.utc).strftime("%Y%m%d %H:%M:%S")
print("Now:" + str(now2) + lastUpdate)
for the differences, please parse string into two datetime objects and calculate the differences in days.
now3 = datetime.now(timezone.utc)
day = datetime.strptime(lastUpdate, '%Y-%m-%d %H:%M:%S%z')
print("now3= "+ str(now3))
print("day= " + str(day))
diffs = now3 - day
print('Total difference in minutes: ', str(diffs.days))
print("Now:" + str(now3) +" "+ lastUpdate + "Diff= " + str(diffs.days))
The datatype of 'now' is datetime and of 'lastUpdate' is str, you cannot get difference between different datatypes. Convert lastUpdate to datetime format first.
import json
from datetime import datetime, timezone
from dateutil import parser
def lambda_handler(event, context):
lastUpdate="2020-09-17 03:59:21+00:00"
lastUpdate = parser.parse("2020-09-17 03:59:21+00:00")
now = datetime.now(timezone.utc)
diff = now - lastUpdate
print("Now:" + str(now) + str(lastUpdate))
strftime-and-strptime-behavior
strftime-and-strptime-format-codes
from datetime import datetime
lastUpdate = "2020-09-17 03:59:21+00:00"
dt: datetime = datetime.strptime(lastUpdate, "%Y-%m-%d %H:%M:%S%z")
print(repr(dt))
# datetime.datetime(2020, 9, 17, 3, 59, 21, tzinfo=datetime.timezone.utc)
dt_str = dt.strftime("%Y-%m-%d %H:%M:%S")
print(repr(dt_str))
# '2020-09-17 03:59:21'
I want to specify the date of the desired format as a file name in this way
;
During [2019-10-01 09:00 ~ 2019-10-02 08:59:59]
Save data to 191001-09.txt
I have no idea about this. I could only follow simple code.
Please let me know how to fix it :
def timeStamped (fname, fmt = '19% m% d-% H {fname} '):
return datetime.datetime.now (). strftime (fmt) .format (fname = fname)
with open (timeStamped ('. txt'), 'a') as f_last:
f_last.write ('data')
Question: Conditional file name from datetime.now()
Import the required objects
datetime
timedelta
from datetime import datetime, timedelta
Define a function that gets the desired file name from a datetime.date object:
def fname_from_date(date):
# Rule 09:00:00 ~ day + 1 08:59:59
midnight = date.replace(hour=0, minute=0, second=0)
begin_of_day = date.replace(hour=9, minute=0, second=0)
end_of_day = date.replace(hour=8, minute=59, second=59)
# Are we between 'midnight' and 'end_of_day'
if date >= midnight and date <= end_of_day:
date = date - timedelta(days=1)
print('\tNext day -1: {}'.format(date))
# 191001-09.txt
fname = date.strftime('%Y%m%d-09')
return fname
Test the function def fname_from_date(... with static dates.
This requires to create a datetime.date object from datestr.
for datestr in ['2019-10-01 09:00:00',
'2019-10-01 11:01:11',
'2019-10-02 07:07:07',
'2019-10-02 08:59:59']:
date = datetime.strptime(datestr, '%Y-%m-%d %H:%M:%S')
print(date)
fname = '{}.txt'.format(fname_from_date(date))
print('\t{}'.format(fname))
Output:
2019-10-01 09:00:00
20191001-09.txt
2019-10-01 11:01:11
20191001-09.txt
2019-10-02 07:07:07
Next day -1: 2019-10-01 07:07:07
20191001-09.txt
2019-10-02 08:59:59
Next day -1: 2019-10-01 08:59:59
20191001-09.txt
Usage:
fname = '{}.txt'.format(fname_from_date(datetime.now()))
I need to calculate the months between two dates. I know it can be easy but I have a code and I can not complete it.
start_date=fields.Date(string="Startdate", requiered=True)
end_date=fields.Date(string="End_date", requiered=True)
duration=fields.Char(string="Duration", computer="_duration")
#api.multi
#api.depends('start_date','end_date')
def _duration(self):
if self.start_date and self.end_date:
start_dt = fields.Datetime.from_string(self.start_date)
finish_dt = fields.Datetime.from_string(self.end_date)
difference = relativedelta(finish_dt, start_dt)
month = difference.month
Try using this code
from datetime import datetime
def diff_month(d1, d2):
return (d1.year - d2.year) * 12 + d1.month - d2.month
or
from datetime import datetime
from dateutil import relativedelta
def get_months(d1, d2):
date1 = datetime.strptime(str(d1), '%Y-%m-%d')
date2 = datetime.strptime(str(d2), '%Y-%m-%d')
print (date2, date1)
r = relativedelta.relativedelta(date2, date1)
months = r.months + 12 * r.years
if r.days > 0:
months += 1
return months
month = get_months('2018-08-13','2019-06-30')
print(month)
Try this code
from datetime import datetime
from dateutil import relativedelta
date1 = datetime.strptime(str('2019-03-01'), '%Y-%m-%d')
date2 = datetime.strptime(str('2019-07-01'), '%Y-%m-%d')
r = relativedelta.relativedelta(date2, date1)
print(r.months)
i am trying to find difference of two datetime variable in python
i tried using direct difference of two variables, tried using strptime() function
from datetime import datetime
time = datetime.now()
#timestamp variable gets time value from database
print "time 1:" + str(timestamp)
print "time 2:" + str(time)
#diff = timestamp-time; #already tried
#diff = datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S") - datetime.strtime(time, "%Y-%m-%d %H:%M:%S") # already tried
diff= datetime.datetime(timestamp, "%Y-%m-%d %H:%M:%S") - datetime.datetime(time, "%Y-%m-%d %H:%M:%S")
print diff
Expect the output in seconds and actual result is type error
You can use total_seconds() on datetime.timedelta to get difference in seconds:
diff = (timestamp-time).total_seconds()
Code:
from datetime import datetime
timestamp = '2019-04-01 07:12:00'
time = '2019-04-01 07:11:0'
print("time 1:" + str(timestamp))
print("time 2:" + str(time))
timestamp = datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S")
time = datetime.strptime(time, "%Y-%m-%d %H:%M:%S")
diff = (timestamp-time).total_seconds()
print(diff)
# 60.0
how can i convert my string of date to a datetime.timedelta() in Python?
I have this code :
import datetime
date_select = '2011-12-1'
delta = datetime.timedelta(days=1)
target_date = date_select + delta
print target_date
thanks in advance ...
You wouldn't convert date_select to a timedelta, instead, you need a datetime object, which can be added to a timedelta to produce an updated datetime object:
from datetime import datetime, timedelta
date_select = datetime.strptime('2011-12-1', '%Y-%m-%d')
delta = timedelta(days=1)
target_date = date_select + delta
print target_date
Or, if you prefer, without the fancy from ... import ... import line:
import datetime # <- LOOK HERE, same as in your example
date_select = datetime.datetime.strptime('2011-12-1', '%Y-%m-%d')
delta = datetime.timedelta(days=1)
target_date = date_select + delta
print target_date
You use strptime to do this.
from datetime import datetime
target_date = datetime.strptime(date_select, '%Y-%m-%d')
from datetime import datetime, timedelta
date_select = '2011-12-1'
new_data = datetime.strptime(date_select, '%Y-%m-%d')
delta = timedelta(days=1)
target_date = date_select + delta
print target_date
You will get 2011-12-02 00:00:00; to strip off the '00:00:00' and get only the date, just add .date() to target_date
print target_date.date()
This should give you the only the date = 2011-12-02