I have two strings in python.
time_array1='09-JAN-2014 01:19'
time_array2='09-JAN-2014 01:01'
I need to find the time difference and I am doing:
print time_array1
print time_array2
FMT = '%d-%m-%Y %H:%M'
datetime_object1= datetime.datetime.strptime(time_array1, FMT)
print datetime_object1
datetime_object2= datetime.datetime.strptime(time_array2, FMT)
print datetime_object2
diff=datetime_object1 - datetime_object2
print diff
but I am getting the following error:
datetime_object1= datetime.datetime.strptime(time_array1, FMT)
AttributeError: type object 'datetime.datetime' has no attribute 'strptime'
Is there any alternative way through which I can do it. It seems the python library doesn't have strptime attribute.
The strptime method was added in python 2.5; if you are using an older version use the following code instead:
import datetime, time
datetime_object1 = datetime.datetime(*time.strptime(time_array1, FMT)[:6])
Your months are abbreviations, use the %b to parse that instead of %m.
Demo:
>>> import datetime, time
>>> time_array1='09-JAN-2014 01:19'
>>> time_array2='09-JAN-2014 01:01'
>>> FMT = '%d-%b-%Y %H:%M'
>>> datetime.datetime(*time.strptime(time_array1, FMT)[:6])
datetime.datetime(2014, 1, 9, 1, 19)
>>> datetime.datetime(*time.strptime(time_array2, FMT)[:6])
datetime.datetime(2014, 1, 9, 1, 1)
Related
I have a JSON object with a date that returns
print row['ApplicationReceivedDateTime']
/Date(1454475600000)/
how do I process this using the pythons datetime module?
print type(row['ApplicationReceivedDateTime'])
returns <type 'unicode'>
print repr(row['ApplicationReceivedDateTime'])
returns u'/Date(1454475600000)/'
That looks like milliseconds. Try dividing by 1000.
import datetime as dt
>>> dt.datetime.fromtimestamp(1454475600000 / 1000)
datetime.datetime(2016, 2, 2, 21, 0)
If the date is in the string format per your question, extract the numeric portion using re.
date = '/Date(1454475600000)/'
>>> dt.datetime.fromtimestamp(int(re.findall(r"\d+", date)[0]) / 1000)
datetime.datetime(2016, 2, 2, 21, 0)
You probably want
datetime.datetime.strptime(string_date, "%Y-%m-%d %H:%M:%S.%f")
And the values of Year, Month, Day, Hour, Minute, Second and F, for that you can write a manual function for that like this
def generate_date_time_str(date_str):
"""Login to parse the date str"""
return date_str
the date_str will look link this
"%Y-%m-%d %H:%M:%S.%f"
There is no python module directly convert any random date str to DateTime object
You can use re to get the integer value and then use datetime.datetime.fromtimestamp to get the date value:
from datetime import datetime
import re
string_time = row['ApplicationReceivedDateTime']
parsed_time = int(re.search('\((\d+)\)', string_time)[1]) / 1e3 #1e3 == 1000
rcvd_date = datetime.fromtimestamp(parsed_time)
print(rcvd_date.strftime('%Y-%m-%d %H:%M:%S'))
Prints:
'2016-02-03 05:00:00'
I am trying to remove the milliseconds(28109) from this string 2017-09-12 22:33:55.28109 in Python.
code:
import datetime as dt
from datetime import date,datetime
created_date = datetime.fromtimestamp(ctime)
d=datetime.strptime(created_date, "%Y-%m-%d %H:%M:%S.%fZ")
created_date = datetime.strftime(d, "%m/%d/%Y %I:%M:%S %p")
print(created_date)
Error:
`d=datetime.strptime(created_date, "%Y-%m-%d %H:%M:%S.%fZ")`
TypeError: must be str, not datetime.datetime
You already have a datetime object, you do not need to parse it again. The datetime.fromtimestamp() call was enough.
Remove the datetime.strptime() line.
created_date = datetime.fromtimestamp(ctime)
created_date = created_date.strftime("%m/%d/%Y %I:%M:%S %p")
print(created_date)
I also changed your strftime() call, it is a method, you just call it on the datetime object you have.
I suspect that you printed the return value of the datetime.fromtimestamp() call, and got confused. The str() conversion of a datetime() instance formats the value as a ISO 8601 string. Note that even if you did have a string, you used the wrong format (there is no timezone in that string, so %Z does not apply).
If you needed a datetime object, rather than a formatted string, you could also just have converted your timestamp to an integer; the microseconds are captured in the decimal portion of the timestamp:
>>> ctime = 1505252035.28109
>>> datetime.fromtimestamp(ctime)
datetime.datetime(2017, 9, 12, 22, 33, 55, 281090)
>>> datetime.fromtimestamp(int(ctime))
datetime.datetime(2017, 9, 12, 22, 33, 55)
>>> print(_)
2017-09-12 22:33:55
You can use time as well to achieve what you want.
import time
ctime = "2017-09-12 22:33:55.28109"
x = time.strptime(ctime.split('.')[0],'%Y-%m-%d %H:%M:%S')
x = time.strftime('%m/%d/%Y %I:%M:%S %p', x)
print (x)
'09/12/2017 10:33:55 PM'
I have a situation where I need to find the previous date from the date_entry where the date_entry is string, I managed to do this:
>>> from datetime import timedelta, datetime
>>> from time import strptime, mktime
>>> date_str = '20130723'
>>> date_ = strptime(date_str, '%Y%m%d')
>>> date_
time.struct_time(tm_year=2013, tm_mon=7, tm_mday=23, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=204,tm_isdst=-1)
>>> datetime.fromtimestamp(mktime(date_))-timedelta(days=1)
datetime.datetime(2013, 7, 22, 0, 0)
>>>
But, for this I have to import the modules timedelta, datetime, strptime and mktime. I think this really an overkill to solve this simple problem.
Is there any more elegant way to solve this (using Python 2.7) ?
Just use datetime.datetime.strptime class method:
>>> import datetime
>>> date_str = '20130723'
>>> datetime.datetime.strptime(date_str, '%Y%m%d') - datetime.timedelta(days=1)
datetime.datetime(2013, 7, 22, 0, 0)
Chosen answer is old and works on python 2, returns bellow error for python 3.
Error:
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
Fix + Doing it with PYTHON 3 :
from datetime import datetime,timedelta
date_str = '20130723'
datetime.strptime(date_str, '%Y%m%d') - timedelta(days=1)
Also, use up to date document on Python 3 here: https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime
After I parsed a date in Python I need to patch it. But structure time.struct_time has read-only properties only:
parsed = time.strptime("23:59", "%H:%M")
parsed.tm_year = 2011
> TypeError: readonly attribute
How do I get a patched datetime value in a short & clever way?
Use datetime:
>>> p = datetime.datetime.strptime("23:59", "%H:%M")
>>> p = p.replace(year=2011)
>>> p
datetime.datetime(2011, 1, 1, 23, 59)
I have...
entity = simplejson.dumps({"a":unicode(datetime.datetime.utcnow())})
How do I convert the datetime (that was converted to unicode) back to datetime again?
So that I can do something like...
entity2 = simplejson.loads(entity)
#your answer here..
add5 = entity2["a"] + datetime.timedelta(minutes=5)
Thanks!
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
Do the following before serializing:
time = datetime.strftime(time, DATETIME_FORMAT)
Do the following after unserializing:
time = datetime.strptime(time, DATETIME_FORMAT)
example:
>>> from datetime import datetime
>>> DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
>>> time = datetime.now()
>>> time
datetime.datetime(2011, 5, 5, 3, 1, 45, 646302)
>>> time = time.strftime(DATETIME_FORMAT)
>>> time
'2011-05-05 03:01:45'
>>> import json
>>> time = json.loads(json.dumps(time))
>>> time
'2011-05-05 03:01:45'
>>> time = datetime.strptime(time, DATETIME_FORMAT)
>>> time
datetime.datetime(2011, 5, 5, 3, 1, 45)
In case you find this somewhat inelegant, you might consider a custom json encoder/decoder. I personally have tried the ones in the default json package, but gave up pulling my hair out with cryptic error messages. If you go this path, I might recommend a third party json package.
Use datetime.datetime.strptime.
dt = datetime.datetime.strptime(entity2['a'], '%Y-%m-%d %H:%M:%S.%f')