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
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 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)
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')
I get the server date and I need to get the difference of this date from GMT
I get
Datetime = "2011-04-27 2:17:45"
I would like to get the result like
Datetime = "2011-04-27 2:17:45 +0500"
Try this:
import datetime, pytz
now = datetime.datetime.now(pytz.timezone('Asia/Kolkata'))
print now.strftime('%Y-%m-%d %H:%M:%S %z')
# prints: '2011-04-27 13:56:09 +0530'
From the example you have given, it looks to me that what you are looking for is datetime.isoformat. The example in the page shows how to convert the datetime values to the ISO format with the time zone information.
To do this, you have to know the timezone (or the UTC offset) of the server date. What you have here is a "naive" date, without timezone info, you can't guess the UTC difference.
I think the datetime module is what you need here:
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2011, 4, 27, 11, 8, 26, 149000)
>>> datetime.utcnow()
datetime.datetime(2011, 4, 27, 8, 8, 47, 712000)
For a difference between two dates:
>>> dtnow = datetime.now()
>>> dtutc = datetime.utcnow()
>>> dtnow - dtutc
datetime.timedelta(0, 10792, 847000)
Look up the datetime module and the relevant classes in Python's docs.
A very powerful extension of the datetime standard python library is the dateutil one, that allows you to easily:
set the delta of your time zone:
parse dates with various convenient options (in our case we will use the default option, which will allow us to set our time zone)
So 1st set time zone, and default date with this zone:
>>> from datetime import datetime
>>> from dateutil import parser
>>> from dateutil.tz import tzoffset
>>> tz_plus_5 = tzoffset(None, 5 * 60 * 60) # offset is in seconds !
>>> default = datetime.now(tz_plus_5)
Now use this default date in the parsing:
>>> Datetime = "2011-04-27 2:17:45"
>>> my_date = parser.parse(Datetime, default=default)
>>> my_date
datetime.datetime(2011, 4, 27, 2, 17, 45, tzinfo=tzoffset(None, 18000))
>>> my_date.strftime("%Y-%m-%d %H:%M:%S %z")
'2011-04-27 02:17:45 +0500'
For those that simply need to get the offset between local time and UTC, the time module has an attribute time.altzone that specifies the difference between UTC and local time in seconds:
The offset of the local DST timezone, in seconds west of UTC, if one is defined. This is negative if the local DST timezone is east of UTC (as in Western Europe, including the UK). Only use this if daylight is nonzero.
Here's an example of how it works:
>>> datetime.now().isoformat()
'2011-09-01T17:26:46.971000'
>>> datetime.utcnow().isoformat()
'2011-09-01T15:27:32.699000'
>>> time.altzone / (60*60)
-2
Doesn't get much cleaner than that.
I am storing a datetime string in a database. Now I face a problem. When I fetch the string from the database, I need to convert it back to a datetime object...
Any easy way to do that?
The string of datetime looks like:
2010-11-13 10:33:54.227806
You want datetime.strptime(date_string, format).
from datetime import datetime
datetime.strptime("2010-11-13 10:33:54.227806", "%Y-%m-%d %H:%M:%S.%f")
For details on the format string, see http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior
I sugggest you install python-dateutilt:
from dateutil import parser
d = parser.parse(yourstring)
This library gets a datetime object from your date-string in a 'smart' way...
# time tuple to datetime object
time_tuple = (2008, 11, 12, 13, 51, 18, 2, 317, 0)
dt_obj = datetime(*time_tuple[0:6])
print repr(dt_obj)
# date string to datetime object
date_str = "2008-11-10 17:53:59"
dt_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print repr(dt_obj)
# timestamp to datetime object in local time
timestamp = 1226527167.595983
dt_obj = datetime.fromtimestamp(timestamp)
print repr(dt_obj)