How to change the format of the date in Python? - python

I have a date as "1-Jun". How can I convert this to 01/06? I am using Strptime. I thought this is going to be easy but it is not.
Error that I am getting: time data '1-Jun' does not match format '%d-%Mmm'.
This is the command I am using. Can anyone help me with this?
datetime.datetime.strptime(date, '%d-%Mmm').strftime('%m/%d')

There's no such format as %Mmm, what you need to match Jun is %b ("Locale's abbreviated month name"). Also, if you want 01/06 rather than 06/01 it is going to be '%d/%m' in strftime:
print(datetime.datetime.strptime('1-Jun', '%d-%b').strftime('%d/%m'))

Related

Error in python while converting string to datetime with timezone

Code:
pd.to_datetime(dataset['startdate'] ,format="%Y-%m-%d %H:%M:%S%Z")
I got following error
ValueError: time data '2020-02-25 14:56:05+01' does not match format '%Y-%m-%d %H:%M:%S%Z' (match)
help much appreciate.
Your format has a %Z (uppercase) at the end, which according to docs timezone name (like GMT, PSD …). You probably want to use %z (lowercase) which is UTC offset (like ±HHMM[SS[.ffffff]]). However not sure if that would work +01, you might need +0100.
Times series data contains +01 and +02 as well due to daylight saving. That was causing an error. Should be using %z as well

python method to convert string in format "11th November" into a date

I am using python in scrapy and collecting a bunch of dates that are stored on a web page in the form of text strings like "11th November" (no year is provided).
I was trying to use
startdate = '11th November'
datetime.strptime(startdate, '%d %B')
but I don't think it likes the 'th' and I get a
Value error: time data '11th November' does not match format '%d %B'
If I make a function to try to strip out the th, st, rd, nd from the days I figured it will strip out the same text from the month.
Is there a better way to approach turning this into a date format?
For my use, it ultimately needs to be in the ISO 8601 format YYYY-MM-DD
This is so that I can pipe it from scrapy to a database, and from that use it in a Google Spreadsheet for a javascript Google chart. I just mention this because there may be a better place to make the string-to-date change than trying to do it in python.
(As a secondary issue, I also need to figure how to add the right year to the date given that if it says 12th January that would mean Jan 2020 and not 2019. This will be based on a comparison to the date when the scrape runs. i.e. the date today.)
EDIT:
it turned out that the solution required the secondary issue to be addressed as well. Hence the choice of final answer to this question. If the secondary issue of the year was not addressed it defaulted to 1900 which was a problem.
Try this out -
import datetime
datetime_obj = datetime.datetime.strptime(re.sub(r"\b([0123]?[0-9])(st|th|nd|rd)\b",r"\1", startdate) + " " + str(datetime.datetime.now().year), "%d %B %Y")

Python time data does not match format

I have string date data with the following format:
4/16/15 23:50
When I try to convert into a datetime object:
print datetime.datetime.strptime(fecha2, '%d/%m/%y %H:%M')
I get this error:
ValueError: time data '4/16/15 23:50' does not match format '%d/%m/%y %H:%M'
According to this list:
https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior, I am using the right format. Where am I wrong?
you have month and day reversed:
print datetime.datetime.strptime(fecha2, '%m/%d/%y %H:%M')
Also very handy:
from dateutil.parser import parse
parse("4/16/15 23:50")
I know this topic is old but maybe it will help someone. I have faced recently similar issue where the date was actually correctly typed and it throwed the same error:
datetime.datetime.strptime('2018-05-02T14:27:56+00:00', "%Y-%m-%dT%H:%M:%S%z")
error: time data '2018-05-02T14:27:56+00:00' does not match format '%Y-%m-%dT%H:%M:%S%z'
The issue was that i was trying to run the python 3.7 code with python 3.6

Python: trouble converting string into date

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')

Formatting the dates to desired format return invalid dates in python. How to control it?

I have a list of dates like:
['2013-04-06', '06/04/2013', '04/06/2013', 'Apr 06 2013']
I have used datetime.strftime() for converting the dates like ('%d/%m/%Y'), but when it converts the same dates with different formats like:
dd/mm/yyyy and mm/dd/yyyy
'06/04/2013' and '04/06/2013'
It returns the date as it is...
How can I solve my problem?
You can't, at least not with 100 % reliability. If your date formats are this hopelessly mixed, you will never be able to tell if 04/06/2013 is supposed to be April 6th or June 4th.
Your only chance is to take the more common variant and try that first. If that throws an error or returns an implausible date (like one in the future, if those are not permitted), try the next one.
You might also want to look into dateutil. It does its best to parse a date in any given format.
Numeric dates can be ambiguous. There are acouple of solutions;
Use an abbreviated name for the month; both "apr 06 2013" or "6 apr 2013". A downside is that the abbreviations for the month are locale dependent.
Stick to the international standard ISO 8601; YYYY-MM-DD or YYYYMMDD.
If you are getting dates from user input it is impossible to distingiush between MM-DD and DD-MM in all cases. But there are some things that can help. A number >12 is obsiously a day, not a month. If you know that the user is from Europe, the date will probably be DD-MM-YYYY. A person from the USA is more likely to use MM-DD-YYYY.

Categories

Resources