开发者

Now to convert this strings to date time object in Python or django?

开发者 https://www.devze.com 2023-01-20 10:18 出处:网络
Now to convert this strings to date t开发者_Python百科ime object in Python or django? 2010-08-17T19:00:00Z

Now to convert this strings to date t开发者_Python百科ime object in Python or django?

2010-08-17T19:00:00Z
2010-08-17T18:30:00Z
2010-08-17T17:05:00Z
2010-08-17T14:30:00Z
2010-08-10T22:20:00Z
2010-08-10T21:20:00Z
2010-08-10T20:25:00Z
2010-08-10T19:30:00Z
2010-08-10T19:00:00Z
2010-08-10T18:30:00Z
2010-08-10T17:30:00Z
2010-08-10T17:05:00Z
2010-08-10T17:05:00Z
2010-08-10T15:30:00Z
2010-08-10T14:30:00Z

whrn i do this datestr=datetime.strptime( datetime, "%Y-%m-%dT%H:%M:%S" )

it tell me that unconverted data remains: Z


You can parse the strings as-is without the need to slice if you don't mind using the handy dateutil module. For e.g.

>>> from dateutil.parser import parse
>>> s = "2010-08-17T19:00:00Z"
>>> parse(s)
datetime.datetime(2010, 8, 17, 19, 0, tzinfo=tzutc())
>>> 


Use slicing to remove "Z" before supplying the string for conversion

datestr=datetime.strptime( datetime[:-1], "%Y-%m-%dT%H:%M:%S" )

>>> test = "2010-08-17T19:00:00Z"
>>> test[:-1]
'2010-08-17T19:00:00'


Those seem to be ISO 8601 dates. If your timezone is always the same, just remove the last letter before parsing it with strptime (e.g by slicing).

The Z indicates the timezone, so be sure that you are taking that into account when converting it to a datetime of a different timezone. If the timezone can change in your application, you'll have to parse that information also and change the datetime object accordingly.

You could also use the pyiso8601 module to parse these ISO dates, it will most likely also work with slighty different ISO date formats. If your data may contain different timezones I would suggest to use this module.


change your format string to ""%Y-%m-%dT%H:%M:%SZ" so that it includes the trailing Z (which makes it no longer unconverted). Note, however, that this Z perhaps is there to indicate that the time is in UTC which might be something you need to account for otherwise

0

精彩评论

暂无评论...
验证码 换一张
取 消