python time strptime_datetime.strptime()的Python时区'%z'指令不可用

Using '%z' pattern of datetime.strptime()

I have a string text that represent a date and I'm perfectly able to parse it and transform it into a clean datetime object:

date = "[24/Aug/2014:17:57:26"

dt = datetime.strptime(date, "[%d/%b/%Y:%H:%M:%S")

Except that I can't catch the entire date string with the timezone using the %z pattern as specified here

date_tz = 24/Aug/2014:17:57:26 +0200

dt = datetime.strptime(date, "[%d/%b/%Y:%H:%M:%S %z]")

>>> ValueError: 'z' is a bad directive in format '[%d/%b/%Y:%H:%M:%S %z]'

strftime() is implemented per platform

I precise that there is no such a problem with the naive tzinfo directive '%Z'

Workaround : Casting tzinfo string into tzinfo object

I can perfectly make the following workaround by transforming the GST time format string into a tzinfo object [as suggested here][4] using dateutil module

and then insert tzinfo into datetime object

Question: Make %z available for my plateform?

But as I will obviously need %z pattern for further project I would like to find a solution to avoid this workaround and using external module for this simple task.

Can you suggest me some reading on it? I supposed that newer version of python (I'm on 2.7) can handle it but I'd rather not changing my version now for this little but crucial detail.

[EDIT]

Well, seeing comments make me reformulated my question how to parse Email time zone indicator using strptime() without being aware of locale time?

解决方案

strptime() is implemented in pure Python. Unlike strftime(); it [which directives are supported] doesn't depend on platform. %z is supported since Python 3.2:

>>> from datetime import datetime

>>> datetime.strptime('24/Aug/2014:17:57:26 +0200', '%d/%b/%Y:%H:%M:%S %z')

datetime.datetime(2014, 8, 24, 17, 57, 26, tzinfo=datetime.timezone(datetime.timedelta(0, 7200)))

how to parse Email time zone indicator using strptime() without being aware of locale time?

There is no concrete timezone implementation in Python 2.7. You could easily implement the UTC offset parsing, see How to parse dates with -0400 timezone string in python?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值