python datetime strptime does not match format - python

This is the code i want to run
from datetime import datetime
date="08/30/2017 10:02 pm (PDT)"
dt = datetime.strptime(date, '%m/%d/%Y %I:%M %p (%Z)')
date is a string with value 08/30/2017 10:02 PM (PDT)
It looks perfectly fine to me, but python give me this error:
time data '08/30/2017 10:02 PM (PDT)' does not match format '%m/%d/%Y %I:%M %p (%Z)'
The code was ran on a remote machine with python 2.7. However, if I manually type those code into a local python terminal. It works perfectly fine.
Is there any thing that can make the difference?
(I tried to change date between unicode/str, makes no difference)

Check the value of the TZ environment variable. time.strptime uses the TZ variable to disambiguate time zone abbreviations because they would not be unique otherwise. I can reproduce the match error with TZ=Europe/Berlin, but get a successful parse with TZ=America/Tijuana.
Another source for the discrepancy could occur if the other machine has TZ data which uses numeric time zones only, which was a somewhat recent change (in 2017) for certain time zones (which would also mean the machine on which this works would have a woefully outdated time zone database).

Your solution works if you replace PDT with UTC - it seems PDT is not recognized:
from datetime import datetime
date="08/30/2017 10:02 pm (UTC)"
dt = datetime.strptime(date, '%m/%d/%Y %I:%M %p (%Z)')
print(dt) # 2017-08-30 22:02:00
vs.
date="08/30/2017 10:02 pm (PDT)"
dt = datetime.strptime(date, '%m/%d/%Y %I:%M %p (%Z)')
print(dt) # time data '08/30/2017 10:02 pm (PDT)' does not match format '%m/%d/%Y %I:%M %p (%Z)'
(https://pyfiddle.io/ in 2.7 mode)

Related

Parsing a time instant in python

I am relatively new to python.
I have a timestamp of the format - 2016-12-04T21:16:31.265Z. It is of a type string. I want to know how can I parse the above timestamp in python.
I was looking through the datetime library, but seems like it accepts only floats. How do I get the time stamp parsed? I was trying to hunt for something like an equivalent of Instant (in java) for python?
import datetime
time_str = '2016-12-04T21:16:31.265Z'
time_stamp = datetime.datetime.strptime(time_str, "%Y-%m-%dT%H:%M:%S.%fZ")
print(time_stamp)
Reference: https://docs.python.org/2/library/datetime.html; (8.1.7. strftime() and strptime() Behavior)
To parse it according to your current timezone, using the format used by the Unix date command:
import re
from calendar import timegm
from datetime import datetime
from time import localtime, strptime, strftime
fmt = "%a %b %d %H:%M:%S %Z %Y"
ts = "2016-12-04T21:16:31.265Z"
strftime(fmt, localtime(timegm(strptime(re.sub("\.\d+Z$", "GMT", ts), '%Y-%m-%dT%H:%M:%S%Z'))))

Date Conversion Django Error

I have a date here which is Fri Jun 19 02:27:25 PDT 2015 which I get from the DB and I am trying to convert it from PDT to UTC
For which first I am converting it to a datetime object like this:
date_time = datetime.datetime.strptime(date, '%a %b %d %H:%M:%S %Z %Y');
When I run the python file directly, it works, but when this code executes thru the Django framework, I get this error.
ValueError: time data 'Fri Jun 19 02:27:25 PDT 2015' does not match format '%a %b %d %H:%M:%S %Z %Y'
I have a feeling this is because of the timezone, because I have many more date formats which don’t contain timezone and conversion for them works fine. Could you suggest a workaround for this.
This error raised because datetime module not recognize all time-zones, use dateutil module instead of datetime similar below:
from dateutil.parser import parse
parse('Fri Jun 19 02:27:25 PDT 2015')

Today's and tomorrow's date in YYYY-MM-DD format in PST timezone in python

I need to get the date for today and tomorrow in YYYY-MM-DD format in python in PST timezone. The datetime() returns date in UTC. I have an internal JIRA system which uses PST date setting and i want to query that. The code will run in a restricted environment where i can't install any external python modules like the pytz library. I tried in a lot of ways but am unsuccessful.
Is there anyway it can be done in python?
There is confusion about the timezone for datetime.date.today(), http://docs.python.org/2/library/datetime.html It gives local time. Right now it is the 20th in Greenwich, Google:
1:55 AM
Thursday, March 20, 2014 (GMT)
Time in Greenwich, London, UK
In Colorado today() gives the 19th:
>>> import datetime
>>> str(datetime.date.today())
'2014-03-19'
>>> str(datetime.date.today() + datetime.timedelta(1))
'2014-03-20'
>>>
Seems like you can use timedelta for converting UTC to PST and todays date to tomorrows date:
from datetime import datetime, timedelta
print datetime.utcnow() - timedelta(hours=8) //convert to PST
print datetime.utcnow() + timedelta(days=1) //get tomorrow
For ‘YYYY-MM-DD’ format, there is a date.isoformat() method in python docs
I used the below code to get today's date and tomorrow's date in PST.
from datetime import datetime, timedelta
from pytz import timezone
import pytz
/*Timezone aware object*/
utc_now = pytz.utc.localize(datetime.utcnow())
pst_now = utc_now.astimezone(pytz.timezone("America/Los_Angeles"))
file_dt=pst_now.strftime("%Y-%m-%d")
print(file_dt)
curr_time=datetime.utcnow().astimezone(pytz.timezone("America/Los_Angeles")
tom_time=utc_now+datetime.timedelta(days=1)
today=curr_time.strftime("%Y-%m-%d")
tomorrow=tom_time.strftime("%Y-%m-%d")
print("Today is "+today+" and Tomorrow is "+tomorrow)

Using python datetime.datetime.strptime on windows with BST timezone

I need to parse many different dates in many different formats. I am having trouble with the following and wondered if anyopne could explain why;
The following works on a linux system:
from datetime import datetime
datetime.strptime('Tue 23 Aug 2011 09:00:07 PM BST','%a %d %b %Y %H:%M:%S %p %Z')
But running under windows it raises
ValueError: time data does not match format
However, if I try GMT not BST on windows, it works fine;
from datetime import datetime
datetime.strptime('Tue 23 Aug 2011 09:00:07 PM GMT','%a %d %b %Y %H:%M:%S %p %Z')
Is there a reason python does not understand the BST timezone under windows, but it works fine under Linux?
thanks,
Matt.
In my opinion, parsing a three-letter time zone code like this is not a good practice (unless of course you have no choice). For example, "EST" is commonly used in the USA for UTC-4/5 and is also commonly used in Australia. So any support for "EST" must therefore be dependent on locale. It would not surprise me if "BST" was similarly ambiguous.
I highly recommend using the pytz module in which British civil time is given the string identifier Europe/London and UTC is called Etc/UTC. The pytz API will give consistent results regardless of the locale of the user or system running the application.
If you are working on a UI that must be tied to locale, or parsing inputs with formats you cannot change, then consider using a dictionary of abbreviations to pytz timezone objects. For example: {'BST': 'Europe/London'}. Then your application can work with UTC dates and times uniformly, which will greatly reduce the possibility of errors.

How do I find difference between times in different timezones in Python?

I am trying to calculate difference(in seconds) between two date/times formatted as following:
2010-05-11 17:07:33 UTC
2010-05-11 17:07:33 EDT
time1 = '2010-05-11 17:07:33 UTC'
time2 = '2010-05-11 17:07:33 EDT'
delta = time.mktime(time.strptime(time1,"%Y-%m-%d %H:%M:%S %Z"))-\
time.mktime(time.strptime(time2, "%Y-%m-%d %H:%M:%S %Z"))
The problem I got is EDT is not recognized, the specific error is
ValueError: time data '2010-05-11 17:07:33 EDT' does not match format '%Y-%m-%d %H:%M:%S %Z'
Check out the pytz world timezone definitions library.
This library allows accurate and cross platform timezone calculations using Python 2.3 or higher. It also solves the issue of ambiguous times at the end of daylight savings, which you can read more about in the Python Library Reference (datetime.tzinfo).
It takes advantage of the tz database, which should include EDT, and allow you to perform the calculations you need to (and probably more reliably & accurately than your current implementation).
In addition to pytz, check out python-dateutil. The relativedelta functionality is outstanding.
Here's a sample of using them together:
from datetime import datetime
from dateutil.relativedelta import *
import pytz
if __name__ == '__main__':
date_one = datetime.now(pytz.timezone('US/Eastern'))
date_two = datetime.now(pytz.timezone('US/Mountain'))
rdelta = relativedelta(date_one, date_two)
print(rdelta)
From docs for strptime
Support for the %Z directive is based
on the values contained in tzname and
whether daylight is true. Because of
this, it is platform-specific except
for recognizing UTC and GMT which are
always known (and are considered to be
non-daylight savings timezones).

Categories

Resources