简体   繁体   English

将日期转换为字符串以在 python 中进行操作

[英]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.我是 python 的新手,我编写了一个脚本,将输入的字符串日期转换为输出的datetime时间格式。 My problem is that cannot convert the datetime object back to a string for manipulation.我的问题是无法将datetime时间 object 转换回字符串进行操作。 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.我有一个日期,例如2011-08-10 14:50:10我需要做的就是在日期和时间之间添加一个T并在最后添加一个Z unfortunately im using python 2.3 as my application will only accept that.不幸的是,我正在使用 python 2.3,因为我的应用程序只会接受它。

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")))
toValue = fromValue.strftime("%Y-%m-%dT %H:%M:%SZ")

This should work fine.这应该可以正常工作。 datetime.strftime was available on Python 2.3. datetime.strftime在 Python 2.3 上可用。

You'd certainly be better off upgrading to at least Python 2.5 if at all possible.如果可能的话,您当然最好升级到至少Python 2.5。 Python 2.3 hasn't even received security patches in years. Python 2.3 多年来甚至没有收到安全补丁。

Edit: Also, you don't need to initialize or declare variables in Python;编辑:另外,您不需要在 Python 中初始化或声明变量; the fromValue= '' has no effect on your program. fromValue= ''对您的程序没有影响。

Edit 2: In a comment, you seem to have said you have it in a string already in nearly the right format:编辑2:在评论中,您似乎已经说过您已经将它放在一个几乎正确格式的字符串中:

"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.如果你想在它是一个字符串时添加字母。

It looks like you are trying to format the datetime in ISO-8601 format.看起来您正在尝试以ISO-8601格式格式化日期时间。 For this purpose, use the isoformat method.为此,请使用isoformat方法。

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.这是 Python2.3 文档中isoformatparsedate的链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM