Python: trouble converting string into date - python

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

Related

Float to datetime returns wrong output (Same Month) - Python

I have a column of float values which are tweet creation dates. This is the code I used to convert them from float to datetime:
t = 1508054212.0
datetime.utcfromtimestamp(t).strftime('%Y-%m-%d %H:%M:%S')
All the values returned belong to October 2017. However, the data is supposed to be collected over multiple months. So the dates should have different months and not just different Hours, Minutes and Seconds.
These are some values which I need to convert:
1508054212.0
1508038548.0
1506890436.0
Request you to suggest an alternative approach to determine the dates. Thank you.
I assumed df['tweet_creation'].loc[1] will return a number like the examples you gave.
Unfortunately, I don't know what f is, but I assumed it was a float.
My answer is inspired by this other answer: Converting unix timestamp string to readable date. You have a UNIX timestamp, so the easiest way is to use it and not convert it as a string.
from datetime import datetime, timedelta
dtobj = datetime.utcfromtimestamp(int(df['tweet_creation'].loc[1])) + timedelta(days=f-int(f))
To have the string representation you can use the function strftime.

How to change the format of the date in 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'))

Convert json field to datetime in Python

I get time data from API response like '2020-02-25T20:53:06.706401+07:00'. Now I want to convert to %Y-%m-%d %H:%M:%s format. But I do not know exactly standard format of that time data.
Help me find the time format!
In your case you can use datetime.fromisoformat:
from datetime import datetime
datetime_object = datetime.fromisoformat("2020-02-25T20:53:06.706401+07:00")
print(datetime_object.strftime("%Y-%m-%d %H:%M:%s"))
Prints
2020-02-25 20:53:1582656786
Other options:
Use the third party dateutil library
Use datetime.strptime which parses the string according to format
You can convert to a datetime object and then optionally recreate the string in a new format as follows:
from datetime import datetime
d = "2020-02-25T20:53:06.706401+07:00"
dt = datetime.strptime(d, "%Y-%m-%dT%H:%M:%S.%f%z")
# Note the capital S
new = dt.strftime("%Y-%m-%d %H:%M:%S")
However the new value here has lost the timezone offset information. I assume that's OK for you. I also used %S instead of %s since I assume that's really what you want. The lowercase %s wouldn't really make sense, and is also not truly supported by Python.

Unable to convert index to date format

I have data which is in-64 in the Index with values like "01/11/2018" in the index. It is data that has been imported from a csv. I am unable to convert it to a "01-11-2018" format. How do I do this because I get an error message:
'time data 0 does not match format '%Y' (match)'
I got the data from the following website:
https://www.nasdaq.com/symbol/spy/historical
and you can find a ' Download this file in Excel Format ' icon at the bottom.
import datetime
spyderdat.index = pd.to_datetime(spyderdat.index, format='%Y')
spyderdat.head()
How do I format this correctly?
Thanks a lot.
Your format string must match exactly:
import datetime
spyderdat.index = pd.to_datetime(spyderdat.index, format='%d/%m/%Y')
spyderdat.head()
Example w/o spyder:
import datetime
date = "1/11/2018"
print(datetime.datetime.strptime(date,"%d/%m/%Y"))
Output:
2018-11-01 00:00:00
You can strftime this datetime then anyhow you like. See link for formats. Or you store datetimes.
Assuming your input is a string, simply converting the / to - won't fix the issue.
The real problem is that you've told to_datetime to expect the input string to be only a 4-digit year but you've handed it an entire date, days and months included.
If you meant to use only the year portion you should manually extract the year first with something like split.
If you meant to use the full date as a value, you'll need to change your format to something like %d/%m/%Y. (Although I can't tell if your input is days first or months first due to their values.)
The easy way is to try this
datetime.datetime.strptime("01/11/2018", '%d/%m/%Y').strftime('%d-%m-%Y')

Django check if variable contains datetime and format

How do I check if a variable contains a datetime and the format it to just include the date, hour, minutes and seconds. Not milliseconds.
The issue I'm having is that the variable isn't in datetime format as it can either contain text or a date time.
return isinstance(new_value, datetime.datetime)
Therefore running the command above returns false.
If new_value contains 2016-05-24 09:26:51.754000+00:00 how do I format it to look like this : 2016-05-24 09:26:51
At first you need to convert date string to the datetime object, in this way you can check it with 'isinstance()', but I want to suggest better solution, as I think :), because at the Python 2.7, so still popular, we have issue with timezone offset ( %z ) when convert date string to datetime object, so here is my solution without 'strptime' :
from dateutil import parser
date = '2016-05-24 09:26:51.754000+00:00'
try:
# something if format correct
parsed_date = parser.parse(date)
# formatting
print parsed_date.strftime("%Y-%m-%d %H:%M:%S")
except ValueError:
# something if format incorrect
print 'Wrong date format'
Sure, please don't forget to write :
$pip install python-dateutil

Categories

Resources