How can I convert date to string in python? - python

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'

Related

Python - Adding offset to time

I have a time string, say
str = "2018-09-23 14:46:55"
and an offset
offset = "0530"
I want to get str2 with offset added, ie
str2 = "2018-09-23 20:16:55"
Please guide.
You can use the datetime module:
from datetime import datetime, timedelta
x = "2018-09-23 14:46:55"
offset = "0530"
res = datetime.strptime(x, '%Y-%m-%d %H:%M:%S') + \
timedelta(hours=int(offset[:2]), minutes=int(offset[2:]))
print(res)
datetime.datetime(2018, 9, 23, 20, 16, 55)
Use timedelta to add offset to a datetime object.
from datetime import datetime, timedelta
str = "2018-09-23 14:46:55"
str = datetime.strptime(str, "%Y-%m-%d %H:%M:%S")
str2 = str + timedelta(hours=5, minutes=30)
print(str2)

getting incorrect utc to local time for timezone given

If I run this url : https://api.sunrise-sunset.org/json?lat=12.98&lng=77.61&date=2017-08-26
I get sunrise time: "12:38:14 AM"
and this is UTC time, if I convert it to given timezone using :
from datetime import datetime
import pytz
from dateutil import tz
def convertUTCtoLocal(date, utcTime, timezone):
""" converts UTC time to given timezone
"""
to_zone = pytz.timezone(timezone)
from_zone = _tz.gettz('UTC')
utc = _datetime.strptime('%s %s' % (date, utcTime), '%Y-%m-%d %H:%M:%S')
utc = utc.replace(tzinfo=from_zone)
local = utc.astimezone(to_zone)
return str(local.time())
but this returns 18:08:16 which is evening time , so what am I doing wrong here.
given timzone is Asia/Kolkata
Example:
>>> from datetime import datetime
>>> from dateutil import tz
>>> from_zone = tz.gettz('UTC')
>>> to_zone = tz.gettz('Asia/Kolkata')
>>> utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S')
>>> utcTime = "12:38:16" ## from json URL we get AM/PM but I remove it.
>>> utc = datetime.strptime('2017-08-26 {}'.format(utcTime), '%Y-%m-%d %H:%M:%S')
>>> utc
datetime.datetime(2017, 8, 26, 12, 38, 16)
>>> utc = utc.replace(tzinfo=from_zone)
>>> central = utc.astimezone(to_zone)
>>> central
datetime.datetime(2017, 8, 26, 18, 8, 16, tzinfo=tzfile('/usr/share/zoneinfo/Asia/Kolkata'))
The problem was that you had "12:38:16 AM" which is actual "00:38:16" so you can't just strip "AM". I changed your function so it will work with "AM" and "PM" hours, just don't strip "AM" and "PM" before using the function:
import pytz
from _datetime import datetime
from dateutil import tz
def convertUTCtoLocal(date, utcTime, timezone):
""" converts UTC time to given timezone
"""
to_zone = pytz.timezone(timezone)
from_zone = tz.gettz('UTC')
## for formating with AM and PM hours in strptime you need to add
## %p at the end, also instead of %H you need to use %I
utc = datetime.strptime('%s %s' % (date, utcTime), '%Y-%m-%d %I:%M:%S %p')
utc = utc.replace(tzinfo=from_zone)
local = utc.astimezone(to_zone)
return str(local.time())
date = '2017-08-26'
utcTime = '12:38:14 AM' ## Don't strip AM or PM
timezone = 'Asia/Kolkata'
x = convertUTCtoLocal(date, utcTime, timezone)
print(x)
Also, you can see working example here.

Joining 2 time strings

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)

How to convert "2016.05.09 15:45:45" into 1462788945000?

I have no idea how to implement this. Please describe how to do it correctly.
datetest = "2016.05.09" + " "+ "15:45:45"
from datetime import datetime
d = datetime.strptime(datetest, "%Y.%m.%d %H:%M")
epocht = d.strftime("%Y.%m.%d %H:%M:%S")
Check this out:
from datetime import time
timestamp = int(time.mktime(d.timetuple())) * 1000
You can try this -
import time
import datetime
t = datetime.datetime(2016, 5, 9, 15, 45, 45)
print(time.mktime(t.timetuple() * 1000))
from datetime import datetime
import time
datetest = "2016.05.09" + " "+ "15:45:45"
d = datetime.strptime(datetest, "%Y.%m.%d %H:%M:%S")
t = d.timetuple()
res = int(time.mktime(t)) * 1000
print(res) # -> 1462833945000
I use the dateutil parser as it offers some flexibility, but others may disagree
In [1]:
from dateutil.parser import parse as dateparse
datetest = "2016.05.09" + " "+ "15:45:45"
dateparse(datetest).timestamp() * 1000
Out [1]:
1462830345000.0
'dateparse' returns a datetime.datetime object:
In [2]:
dateparse(datetest)
Out[2]:
datetime.datetime(2016, 5, 9, 15, 45, 45)

how to convert string to datetime.timedelta()?

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

Categories