How would I convert a date in string format to compare it with the current time?
I tried this:
import time, datetime
if time.strptime(date.find(text=True), "%a, %d/%m/%Y").now() > datetime.now():
But I get this error:
ValueError: time data u'Dom, 07/02/2016' does not match format '%a, %d/%m/%Y'
Need advice on how to do this.
You need to setup the proper locale before handling language/region specific data.
Try again with
import locale
locale.setlocale(locale.LC_TIME, '')
time.strptime(date_string, "%a, %d/%m/%Y")
The '' tells the library to pickup the current locale of your system (if one is set).
If you need to parse the date in a different locale, the situation is a little bit more complex. See How do I strftime a date object in a different locale? for the gritty details.
It is possible to explicitly set a specific locale, e.g.
locale.setlocale(locale.LC_TIME, 'es_ES.UTF-8')
time.strptime('Dom, 01/02/1903', '%a, %d/%m/%Y')
=> time.struct_time(tm_year=1903, tm_mon=2, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=32, tm_isdst=-1)
but remember, that this setting is global. strptime() does not accept a parameter to specify a particular locale to parse with, it always picks up the global locale.
If the date is user-supplied, I have used dateparser package as a welcome alternative. Especially so, since its parse() function accepts an explicit languages parameter.
Related
I know there are a lot of answers to this question online, but none of them have worked for me. I am trying to convert a date string into a Datetime object, of the following format: yyyy-mm-dd
My date_string is '2017-02-02T00:00:00Z'
I am trying to convert it by doing date_value = datetime.datetime.strptime(date_string, '%Y%m%d') but I'm getting the following error:
ValueError: time data '"2017-02-02T00:00:00Z"' does not match format
'%Y%m%d'
Also, should I be worried about the double quotes around my date_string string?
The second argument in the method strptime is the pattern of your string.
Here is the full list of available code formats. https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
All the remaining "non-informative" characters in your string can simply be put as-is in there correct places.
Thanks to #MrFuppes for this info: you should also parse the trailing "Z" as %z. This will signal python that it's a UTC datetime and not a local datetime.
Your code should be :
date_string = '2017-02-02T00:00:00Z'
date_value = datetime.datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S%z')
As for the extra quotes, that's not wanted. You should try this beforehand :
date_string = date_string.strip("'").strip('"')
If strip() didn't work, you can call eval instead (usually not recommended) :
date_string = eval(date_string)
The solution is to parse your date_string first, and that should help. Using strptime() right away on an unparsed datetime string can sometimes cause problems. Also you shouldn't worry about your double quotes, it's fine.
First, install the python-dateutil library if you haven't already (pip install python-dateutil at the command line). Then test the solution with the following code.
import datetime
import dateutil.parser
date_string = '2017-02-02T00:00:00Z'
#we parse the string, it becomes a datetime object
parsed_date_string = dateutil.parser.parse(date_string)
print(parsed_date_string)
#output looks like this: 2017-02-02 00:00:00+00:00
#now your statement will work
date_value = datetime.datetime.strptime(str(parsed_date_string), '%Y-%m-%d %H:%M:%S%z')
print(date_value)
#output will also be: 2017-02-02 00:00:00+00:00
The strptime() statement worked this time because we parsed our date first with parse(). Note also that to use strptime() we need to cast our parsed_date_string back to a string because parse() converts our original string to an object of class datetime.datetime and strptime() is expecting a string.
Hopefully that helped.
I am converting the datetime into time. My JSON datetime format is "2017-01-02T19:00:07.9181202Z". I have placed my code below:
from datetime import datetime
date_format = datetime.strptime('2017-01-02T19:00:07.9181202Z', '%Y-%m-%dT%H:%M:%S.%fZ')
time = date_format.strftime("%I:%M %p")
print(time)
Error message as below:
After that I read this python date-time document. It says that microsecond digit should be 6. But, JSON date-time microsecond has 7 digit.
Message from Python document:
%f is an extension to the set of format characters in the C standard
(but implemented separately in datetime objects, and therefore always
available). When used with the strptime() method, the %f directive
accepts from one to six digits and zero pads on the right.
I need result like 07:00 PM format. Is there any alternative method?
Thanks in advance.
If you're sure that the input will always be like that, you can just remove the extra digit before passing that string to strptime:
date_format = datetime.strptime('2017-01-02T19:00:07.9181202Z'[:-2] + 'Z', '%Y-%m-%dT%H:%M:%S.%fZ')
This is dirty, but gives the idea - remove the last two characters (the extra digit and "Z"), re-add the "Z".
This question already has answers here:
Python 2.7 how parse a date with format 2014-05-01 18:10:38-04:00 [duplicate]
(2 answers)
Closed 6 years ago.
I am receiving a json that prints time data '2016-04-15T02:19:17+00:00' I I cant seem to figure out the format of this unicode string.
I need to find a difference in time between then and now. The first step in that is to convert the string to structured format and Iam not able to find the format
fmt='"%Y-%m-%d %H:%M:%S %Z'
#fmt='%Y-%m-%d %H:%M:%S.%f'
print datetime.datetime.strptime(result_json['alert_time'], fmt)
I keep getting exception that it is not the same format
time data '2016-04-15T02:19:17+00:00' does not match format '"%Y-%m-%d %H:%M:%S %Z'
There are a few problems with your format. First, it has a double quote " in it. Second, you need to include the T between the date and the time. Third, the timezone offset is not standard. Here is code that will work:
print datetime.datetime.strptime('2016-04-15T02:19:17', '%Y-%m-%dT%H:%M:%S')
If your alert_time is always in GMT, you can just trim the timezone off before calling strptime.
The answer by Brent is the safer and faster option rather than having things going on under the hood. But the amount of times I've had datetime as a frustrating bottleneck not associated with the main problem I wanted to test out, I will also point out that dateparser here has not yet been wrong for me and will take a huge range of inputs.
import dateparser
import datetime
date = '2016-04-15T02:19:17+00:00'
date_parser_format = dateparser.parse(date)
datetime_format = datetime.datetime.strptime('2016-04-15T02:19:17', '%Y-%m-%dT%H:%M:%S')
print date_parser_format
print datetime_format
I'me trying to use this eventCalendar in Django, which saves and shows dates in this format:
2012-02-27T13:15:00.000+10:00
but when I save events in the database, they're saved in this format:
Mon Feb 27 2012 13:15:00 GMT+0330 (Iraq Standard Time)
so events from the database won't appear on the calendar because of this format. How can I convert this format?
I tried some thing like this:
datetime.strptime(mydatetime, "%Y-%m-%dT%H:%M:%S+0000")
but I'm repeatedly getting errors like this:
'module' object has no attribute 'strptime'
Edit:date is in string format
strptime is used to parse a string into a datetime object. The format string indicates how to parse the string, not the format you want the datetime to take when later printed as a string. So first off you need to make the format string match the date format of the input string.
Once you've gotten a datetime from strptime, you can then use strftime with your current format string to get it into the display you want.
That said, though, it appears you've got a problem with your imports. The error seems to indicate that you've done:
import datetime
datetime.strptime(...)
That's incorrect. strptime and strftime are methods off datetime.datetime, so you need to either modify your import like:
from datetime import datetime
Or, modify your call to strptime like:
datetime.datetime.strptime(...)
UPDATE
You're starting off with a string like Mon Feb 27 2012 13:15:00 GMT+0330 (Iraq Standard Time). Python is pretty awesome, but it's not omniscient; if you want to convert this to a datetime you have to tell it how. That's the purpose of the format string you pass to strptime. You need to create a format string that represents your current string date and time as represented in the database (exercise left to reader). Think in reverse, along the lines of it you wanted to actually represent a datetime like that, how would you do it.
This will net you a datetime. From there, you can now format that datetime as a string with strftime, passing the actual format you want, this time.
So the process is:
Create a format string representing your current string from the database
Use that format string as an argument to strptime to get a datetime
Create a format string representing the format you want the date to be in (already done)
Use that format string as the argument to strftime to convert the datetime from step 2 to your desired string.
I have a date string like "2011-11-06 14:00:00+00:00". Is there a way to check if this is in UTC format or not ?. I tried to convert the above string to a datetime object using utc = datetime.strptime('2011-11-06 14:00:00+00:00','%Y-%m-%d %H:%M%S+%z) so that i can compare it with pytz.utc, but i get 'ValueError: 'z' is a bad directive in format '%Y-%m-%d %H:%M%S+%z'
How to check if the date string is in UTC ?. Some example would be really appreciated.
Thank You
A simple regular expression will do:
>>> import re
>>> RE = re.compile(r'^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}[+-]\d{2}:\d{2}$')
>>> bool(RE.search('2011-11-06 14:00:00+00:00'))
True
By 'in UTC format' do you actually mean ISO-8601?. This is a pretty common question.
The problem with your format string is that strptime just passes the job of parsing time strings on to c's strptime, and different flavors of c accept different directives. In your case (and mine, it seems), the %z directive is not accepted.
There's some ambiguity in the doc pages about this. The datetime.datetime.strptime docs point to the format specification for time.strptime which doesn't contain a lower-case %z directive, and indicates that
Additional directives may be supported on certain platforms, but only the ones listed here have a meaning standardized by ANSI C.
But then it also points here which does contain a lower-case %z, but reiterates that
The full set of format codes supported varies across platforms, because Python calls the platform C library’s strftime() function, and platform variations are common.
There's also a bug report about this issue.