Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting a date to string for manipulation in python

I am new to python and i have written a script that converts a string date coming in to a datetime format going out. My problem is that cannot convert the datetime object back to a string for manipulation. i have a date eg 2011-08-10 14:50:10 all i need to to is add a T between the date and time and a Z at the end. unfortunately im using python 2.3 as my application will only accept that.

my code is as follows:

fromValue= ''
fromValue = document.Get(self._generic3)
fromValue = fromValue[:fromValue.rindex(" ")]
fromValue = datetime.datetime.fromtimestamp(time.mktime(time.strptime(fromValue,"%a, %d %b %Y %H:%M:%S")))
like image 826
Clayton Avatar asked Sep 01 '26 23:09

Clayton


2 Answers

toValue = fromValue.strftime("%Y-%m-%dT %H:%M:%SZ")

This should work fine. datetime.strftime was available on Python 2.3.

You'd certainly be better off upgrading to at least Python 2.5 if at all possible. Python 2.3 hasn't even received security patches in years.

Edit: Also, you don't need to initialize or declare variables in Python; the fromValue= '' has no effect on your program.

Edit 2: In a comment, you seem to have said you have it in a string already in nearly the right format:

"2011-08-08 14:15:21"

so just do

'T'.join("2011-08-08 14:15:21".split()) + 'Z'

If you want to add the letters while it's a string.

like image 77
agf Avatar answered Sep 03 '26 13:09

agf


It looks like you are trying to format the datetime in ISO-8601 format. For this purpose, use the isoformat method.

import datetime as dt 
try:
    import email.utils as eu
except ImportError:
    import email.Utils as eu  # for Python 2.3

date_string="Fri, 08 Aug 2011 14:15:10 -0400"
ttuple=eu.parsedate(date_string)
date=dt.datetime(*ttuple[:6])
print(date.isoformat()+'Z')

yields

2011-08-08T14:15:10Z

Here is link to isoformat and parsedate in the Python2.3 docs.

like image 32
unutbu Avatar answered Sep 03 '26 14:09

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!