By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,050 Members | 1,009 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,050 IT Pros & Developers. It's quick & easy.

Python date

P: 7
Hi,

I am using zope with an SQL database in the background. I have a date stored in the database as "2007/08/20 09:27:16.593 GMT+1".

Is there anyway in python to add an int of "60" to the date?
Nov 9 '07 #1
Share this Question
Share on Google+
3 Replies


bartonc
Expert 5K+
P: 6,596
To add "60" days to a string date takes some machinations:
Expand|Select|Wrap|Line Numbers
  1. >>> import time
  2. >>> import datetime as dt
  3. >>> theDate, theTime, theZone = "2007/08/20 09:27:16.593 GMT+1".split()
  4. >>> timeObj = time.strptime(" ".join([theDate, theTime.split('.')[0]]), "%Y/%m/%d %H:%M:%S")
  5. >>> toAdd = dt.timedelta(days = 60)
  6. >>> timeObj
  7. (2007, 8, 20, 9, 27, 16, 0, 232, -1)
  8. >>> dtObj = dt.datetime(*timeObj[:6])
  9. >>> dtObj
  10. datetime.datetime(2007, 8, 20, 9, 27, 16)
  11. >>> dtObj + toAdd
  12. datetime.datetime(2007, 10, 19, 9, 27, 16)
  13. >>> 
Nov 10 '07 #2

bartonc
Expert 5K+
P: 6,596
Of course, if your DB is MySQL you could call ADDDATE():
Expand|Select|Wrap|Line Numbers
  1. SELECT ADDTIME('1997-12-31 23:59:59.999999', '1 1:1:1.000002');
-> '1998-01-02 01:01:01.000001'
Nov 10 '07 #3

bartonc
Expert 5K+
P: 6,596
Hi,

I am using zope with an SQL database in the background. I have a date stored in the database as "2007/08/20 09:27:16.593 GMT+1".

Is there anyway in python to add an int of "60" to the date?
Here's a slightly more complete example:
Expand|Select|Wrap|Line Numbers
  1. import time
  2. import datetime as dt
  3. theDate, theTime, theZone = "2007/08/20 09:27:16.593 GMT+1".split()
  4. noDec = theTime.split('.')[0]
  5. timeObj = time.strptime(" ".join([theDate, noDec]), "%Y/%m/%d %H:%M:%S")
  6. print timeObj
  7. toAdd = dt.timedelta(days = 60)
  8. dtObj = dt.datetime(*timeObj[:6])
  9. print repr(dtObj)
  10. strToInsert = " ".join([str(dtObj + toAdd), theZone])
  11. print strToInsert
  12.  
  13. # output
  14. (2007, 8, 20, 9, 27, 16, 0, 232, -1)
  15. datetime.datetime(2007, 8, 20, 9, 27, 16)
  16. 2007-10-19 09:27:16 GMT+1
Nov 11 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.