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)
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 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)
I'm using the Google Calendar API.
I've read the quickstart
> eventsResult = service.events().list(
calendarId='primary', timeMin=now, maxResults=10, singleEvents=True,
orderBy='startTime').execute()
But I tried to add a timeMax parameter to filter the event i got.
I wish to get the event from now to the end of today.
I start at:
> import datetime
now = datetime.datetime.now()
then I got:
AttributeError: module 'datetime' has no attribute 'now'
I read that most coder is confused by the datetime.datetime.
I propose to use the module time instead. With the function localtime with no argument passed you can generate a timestamp with the accuracy of a second.
Example
>>> import time
>>> ts = time.localtime()
>>> print ts
time.struct_time(tm_year=2017, tm_mon=8, tm_mday=9, tm_hour=12, tm_min=39, tm_sec=50, tm_wday=2, tm_yday=221, tm_isdst=0)
>>> print ts.tm_year, ts.tm_mon, ts.tm_mday
2017 8 9
>>> print ts[3:6]
(12, 39, 50)
As you see, you have several methods to extract the information from the timestamp.
[EDIT]
If the ISO-Format of the timestamp is important, ignore my answer... ;)
>>> import datetime as dt
>>> from datetime import date,timedelta
>>> dt.datetime.today() - timedelta(days=-1)
#datetime.datetime(2017, 8, 10, 18, 16, 29, 785131)
>>> Td = dt.datetime.today() - timedelta(days=-1)
>>> Td
#datetime.datetime(2017, 8, 10, 18, 16, 41, 786500)
>>> Td = Td.isoformat()
>>> Td
#'2017-08-10T18:16:41.786500'
>
I finally solved this problem with datetime.
import datetime
now = datetime.datetime.now()
night = now.replace(hour=23, minute=59)
#I'm at UTC+8
utcNow = now-datetime.timedelta(hours=8)
utcnight = night - datetime.timedelta(hours=8)
print (utcNow.isoformat() + 'Z')
print(utcnight.isoformat() + 'Z')
2017-08-10T02:48:16.413384Z
2017-08-10T15:59:16.413384Z
for my local time it is:
2017-08-10 10:48:16.413384Z
2017-08-10 23:59:16.413384Z
I have JSON response object with string representing date and time:
"event":{
"type":"Type",
"date-time":"\/Date(928142400000+0200)\/",
},
I am not sure:
what format is that
how can I parse it in python app
how can I convert python date into this format
Any suggestions?
928142400000 is the time in milliseconds since the UNIX epoch, +0200 is the timezone.
With the dateutil library or datetime.timezone() objects you can model the timezone offset, the timestamp itself is parsable with datetime.datetime.fromtimestamp(), provided you divide the value by 1000.0:
import datetime
import re
timestamp_parse = re.compile(r'Date\((\d+)([+-]\d{4})\)')
timestamp, offset = timestamp_parse.search(datetime_value).groups()
tzoffset = datetime.timedelta(hours=int(offset[1:3]), minutes=int(offset[3:]))
if offset[0] == '-':
tzoffset *= -1
tzoffset = datetime.timezone(tzoffset)
dt = datetime.datetime.fromtimestamp(int(timestamp) / 1000.0).replace(tzinfo=tzoffset)
The dateutil.tz.tzoffset() object version is similar:
import datetime
import re
import dateutil.tz
timestamp_parse = re.compile(r'Date\((\d+)([+-]\d{4})\)')
timestamp, offset = timestamp_parse.search(datetime_value).groups()
tzoffset = int(offset[1:3]) * 3600 + int(offset[3:]) * 60
if offset[0] == '-':
tzoffset *= -1
tzoffset = dateutil.tz.tzoffset(None, tzoffset)
dt = datetime.datetime.fromtimestamp(int(timestamp) / 1000.0).replace(tzinfo=tzoffset)
Demo:
>>> import datetime
>>> import re
>>> datetime_value = "/Date(928142400000+0200)/"
>>> timestamp_parse = re.compile(r'Date\((\d+)([+-]\d{4})\)')
>>> timestamp, offset = timestamp_parse.search(datetime_value).groups()
>>> tzoffset = datetime.timedelta(hours=int(offset[1:3]), minutes=int(offset[3:]))
>>> if offset[0] == '-':
... tzoffset *= -1
...
>>> tzoffset = datetime.timezone(tzoffset)
>>> datetime.datetime.fromtimestamp(int(timestamp) / 1000.0).replace(tzinfo=tzoffset)
datetime.datetime(1999, 5, 31, 10, 20, tzinfo=datetime.timezone(datetime.timedelta(0, 7200)))
is there any way to pass a datetime directly in this format?
mydate = datetime.datetime.now()
myxmldate = '<start>%??</start>' % mydate
or have i to pass like a string?
I need to pass to an xml a datetime structure.
thanks
Try with datetime.isoformat()
mydate = datetime.datetime.now()
myxmldate = '<start>%s</start>' % mydate.isoformat()
Try to reed for 2.6:
>>> mydate.isoformat()
'2002-03-11'
>>> mydate.strftime("%d/%m/%y")
'11/03/02'
>>> mydate.strftime("%A %d. %B %Y")
'Monday 11. March 2002'
And for version 3 Using type-specific :
>>> import datetime
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2010-07-04 12:15:58'
Since you haveXML, it makes sense to use an XML parser. For example, with lxml:
import lxml.etree as ET
import datetime
mydate = datetime.datetime.now()
doc = ET.fromstring('<start>%??</start>')
for start in doc.xpath('//start'):
start.text = start.text.replace('%??',str(mydate))
print(ET.tostring(doc))
yields
<start>2011-11-07 12:28:58.883274</start>