How to convert string with UTC offset

2024/10/12 12:34:29

I have date as

In [1]: a = "Sun 10 May 2015 13:34:36 -0700"

When I try to convert it using strptime, its giving error.

In [3]: datetime.strptime(a, "%a %d %b %Y %H:%M:%S %Z"...: )
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-3-973ef1c6daca> in <module>()
----> 1 datetime.strptime(a, "%a %d %b %Y %H:%M:%S %Z"2 )
/usr/lib/python2.7/_strptime.pyc in _strptime(data_string, format)323     if not found:324         raise ValueError("time data %r does not match format %r" %
--> 325                          (data_string, format))326     if len(data_string) != found.end():327         raise ValueError("unconverted data remains: %s" %
ValueError: time data 'Sun 10 May 2015 13:34:36 -0700' does not match format '%a %d %b %Y %H:%M:%S %Z'
In [6]: datetime.strptime(a, "%a %d %b %Y %H:%M:%S %z")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-6-e4870e34edda> in <module>()
----> 1 datetime.strptime(a, "%a %d %b %Y %H:%M:%S %z")
/usr/lib/python2.7/_strptime.pyc in _strptime(data_string, format)315                 del err316                 raise ValueError("'%s' is a bad directive in format '%s'" %
--> 317                                     (bad_directive, format))318             # IndexError only occurs when the format string is "%"319             except IndexError:
ValueError: 'z' is a bad directive in format '%a %d %b %Y %H:%M:%S %z'

As per doc, correct format is %z, but I might missing some part.

Answer

From the link you provided for the python doc, I found that you are using Python 2.7

It looks as if strptime doesn't always support %z. Python appears to just call the C function, and strptime doesn't support %z on your platform.

Note: from Python 3.2 onwards it will always work.

I am using Python 3.4 in which it is working fine

>>> a = "Sun 10 May 2015 13:34:36 -0700"
>>> datetime.strptime(a, "%a %d %b %Y %H:%M:%S %z")

Update using dateutil

$ pip install python-dateutilfrom dateutil import parser
parsed_date = parser.parse(date)>>> parsed_date
datetime.datetime(2015, 3, 14, 18, 43, 19)
https://en.xdnf.cn/q/118203.html

Related Q&A

regex multiline not working on repeated patterns

I am trying to get a regex expression to match multiple patterns with multilines but it keeps matching everything. For instance I want to match two times this code:STDMETHOD(MyFunc)( D2D1_SIZE_U size, …

Django Rest Framework slug_field error

I have this serializer and model. I want to show in my API the field username of User model, but I receive this error.AttributeError at /api/v1/client_share_requests/1/Profile object has no attribute u…

Django - 500 internal server error no module named django

django return 500 internal server error (apache 2.4.10, ubuntu 15.04, django 1.9.6)apache log:[wsgi:warn] mod_wsgi: Compiled for Python/3.4.2. [wsgi:warn] mod_wsgi: Runtime using Python/3.4.3. [mpm_eve…

Unable to connect to Google Bigtable using HBase REST api

Following this example, running the test script "python put_get_with_client.py" results in a 400 error (Bad Request).Bad requestjava.lang.ClassCastException: org.apache.hadoop.hbase.client.Bi…

HTML form button to run PHP to execute Python script

I am building an HTML document that is meant to run locally. On it is a button that I would like to have run a Python script when clicked. Im trying to use a PHP-generated button. Theres no input or ou…

Python - finding time slots

I am writing a small Python script to find time available slots based off calendar appointments. I was able to reuse the code on the post here: (Python - Algorithm find time slots).It does seem to wor…

ReportLab - error when creating a table

This is the first time Ive used ReportLab, I have tried to edit an existing script that does exactly what I want to do, but I get the following error, when I try and run the script.Script - import os, …

Secure login with Python credentials from user database

I like to create a secure login with Python but need to check the user table from a database, so that multiple users can log in with their own password. Mainly like this, works like a charm but not sec…

count number of names in list in python [duplicate]

This question already has answers here:How to count the frequency of the elements in an unordered list? [duplicate](33 answers)Closed 6 years ago.i have one list wich has names in it:names = [test,hal…

tensorflow logits and labels must be same size

Im quite new to tensorflow and python, and currently trying to modify the MNIST for expert tutorial for a 240x320x3 image. I have 2 .py scripttfrecord_reeader.pyimport tensorflow as tf import numpy as…