I'm using the Paypal API and I get back a timestamp in the following format. I try to parse this to a datetime object using strptime, but I get the following error:
(Pdb) datetime.strptime('2012-03-01T10:00:00Z','%Y-%M-%dT%H:%M:%SZ')
*** error: redefinition of group name 'M' as group 5; was group 2
Also, as this format is supposed to be quite a standard format isn't there a function available for this?
EDIT:
Ok seems to be a typo. First %M should be %m
The parser from dateutil is your friend.
You'll have to pip install dateutil but you've save bags and bags of date conversion code:
pip install python-dateutil
You can use it like this.
from dateutil import parser
ds = '2012-03-01T10:00:00Z' # or any date sting of differing formats.
date = parser.parse(ds)
You'll find you can deal with almost any date string formats with this parser and you'll get a nice standard python date back
Looks like you're mixing %M (minute) and %m (month).
The problem is that you use %M twice. Use %m for the months:
>>> datetime.strptime('2012-03-01T10:00:00Z','%Y-%m-%dT%H:%M:%SZ')
datetime.datetime(2012, 3, 1, 10, 0)
You have a typo. %M is used twice. You meant to use %m for the month. From the docs:
%m Month as a decimal number [01,12].
%M Minute as a decimal number [00,59].
Related
I'm trying to parse dates in the form of "Sept 9, 2021" using datetime
I was trying the following format:
"%m %d, %y" but it raises a ValueError while I'm trying to convert it
(i.e using int(datetime.strptime("Sept 9, 2021","%m %d, %y").timestamp()))
How can I tell which format am I supposed to use?
Thanks
For strptime there are different format code than usual.
You use %b to refer to a Three-digit string month, which means that you must use Sep instead of Sept, and you use %Y to convert a 4 digit year.
So the code would be like the following
int(datetime.datetime.strptime("Sep 9, 2021", "%b %d, %Y").timestamp())
# 1631138400
For more information see Format Codes.
To my knowledge the key work for September is Sep (not Sept).
You can check this link for more details on that: Python Date abbreviation
I advice you to use something similar to this snippet of code:
from datetime import datetime
date_s = "Sep 9, 2021"
datetime_object = datetime.strptime(date_s.upper().replace("SEPT", "SEP"), '%b %d, %Y')
print(datetime_object)
You can also check this Stack thread that seem similar to your question:
Date Handling in Python for Sept
There are a couple of ways how to get the timestamp from your string:
First solution is to use dateparser module from PyPi (pip install dateparser). This module can help you to get datetime object from any string which is similar to datetime string.
Solution:
import dateparser
date_time_object = dateparser.parse("Sept 9, 2021").timestamp()
print(date_time_object)
Result: 1631127600.0
Another issue is that your string contains one unnecessary string in name of month so this solution is a bit wrong and won't help you but only for understanding, I will offer this:
Solution:
from datetime import datetime
time_stamp = int(datetime.strptime("Sep 9, 2021","%b %d, %Y").timestamp())
print(time_stamp)
Result: 1631127600
I am currently having an issue converting an incoming datetime string to a datetime object using Python's built in strptime() method. Here is what I currently have:
def fixDateTimeField(datetimeString):
# Convert from 2012-08-07T00:00:00Z to 2012-08-07T00:00:00.000Z
datetime_object = datetime.strptime(datetimeString, "%y-%m-%dT%H:%M:%SZ")
return datetime_object
Like the comment says, I am trying to convert the string "2012-08-07T00:00:00Z" to a datetime object that looks like 2012-08-07T00:00:00.000Z but I am getting an error in my console that says: "ValueError: time data '2012-08-07T00:00:00Z' does not match format '%y-%m-%dT%H:%M:%SZ'". The format seems correct to me and i'm not seeing the issue.
Thanks in advance!
%y is for two-digit years. You have a four-digit year.
Try using %Y instead.
>>> from datetime import datetime
>>> datetimeString = "2012-08-07T00:00:00Z"
>>> print(datetime.strptime(datetimeString, "%Y-%m-%dT%H:%M:%SZ"))
2012-08-07 00:00:00
A nice way to parse your iso-8601 datetime string "2012-08-07T00:00:00Z" to a datetime object is using dateutil.
import dateutil.parser
yourdate = dateutil.parser.parse(datestring)
With strptime:
datetime.datetime.strptime( "2007-03-04T21:08:12", "%Y-%m-%dT%H:%M:%S")
Works. As an other answer said, the Y must be capitalized for strptime to work with 4 digit years.
I'm using the following code:
data['Input_volTargetStart'][1]>time.strptime(data['Dates'][1], "%d %b $y")
When I try to run it, I get this error:
ValueError: time data '04-Jun-99' does not match format '%d %b $y'
I have tried possibly all combinations but am unable to get the result for this conversion.
You can actually put the dashes ('-') as part of the format, i.e "%d-%b-%y".
This is what you'll need.
from datetime import datetime
a = "04-Jun-99"
frmt = datetime.strptime(a, "%d-%b-%y")
print(frmt)
>>1999-06-04 00:00:00
Implement that example into your code to get proper output.
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]'
Because as this bug report says
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?
In continue to #j-f-sebastians 's answer, here is a fix for python 2.7
Instead of using:
datetime.strptime(t,'%Y-%m-%dT%H:%M %z')
use the timedelta to account for the timezone, like this:
from datetime import datetime,timedelta
def dt_parse(t):
ret = datetime.strptime(t[0:16],'%Y-%m-%dT%H:%M')
if t[17]=='+':
ret-=timedelta(hours=int(t[18:20]),minutes=int(t[20:]))
elif t[17]=='-':
ret+=timedelta(hours=int(t[18:20]),minutes=int(t[20:]))
return ret
print(dt_parse('2017-01-12T14:12 -0530'))
The Answer of Uri is great, saved my life, but when you have
USE_TZ = True you need to be careful with the time, for avoid the warning "RuntimeWarning: DateTimeField" is better if you add the utc to the return.
import pytz
from datetime import datetime, timedelta
def dt_parse(t):
ret = datetime.strptime(t[0:19],'%Y-%m-%dT%H:%M:%S')
if t[23]=='+':
ret-=timedelta(hours=int(t[24:26]), minutes=int(t[27:]))
elif t[23]=='-':
ret+=timedelta(hours=int(t[24:26]), minutes=int(t[27:]))
return ret.replace(tzinfo=pytz.UTC)
I am somewhat new to Python and have a seemingly simple question.
I have a python script that interacts with an API (RHN Satellite if you're curious). This API returns a date in the form of a string and it always trims leading 0's. For example, 6/1/13 or 10/9/12. I need to convert this string to a date and determine the day of the year it is.
Here is what I know:
today = datetime.datetime.now()
print today.strftime('%j')
...will return today's day of year (175). This works fine for a datetime object but I am having trouble converting the string given by the API to an actual date. If I use:
date = datetime.datetime.strptime(var, '%m/%d/$y')
I get error:
ValueError: time data '5/2/13' does not match format '%m/%d/$y'
I'm guessing because it's expecting leading 0's ? How do I get around this?
In the end, I am trying to subtract the variable date given from the current date but I can't do that until I convert the string.
Thanks for the help!
I think you just have a typo, use %y instead of $y:
date = datetime.datetime.strptime(var, '%m/%d/%y')
This code works for me, provided you change $y to %y in the format code.
Correct the $y to %y and I'd use format instead of strftime:
from datetime import datetime
print format(datetime.strptime('5/2/13', '%m/%d/%y'), '%j')