Django check if variable contains datetime and format - python

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

Related

Converting string to datetime with strptime in Python

I'm trying to convert a string to datetime with dd/mm/YYYY format, but the function "strptime" seems isn't working properly. The result format isn't in the same that i am specifying in the function.
import datetime
from datetime import datetime
from datetime import date
today = date.today()
print (today)
today = today.strftime("%d-%m-%Y %H:%M:%S")
print (today)
today = datetime.strptime(today, "%d-%m-%Y %H:%M:%S")
print (today)
My output is this:
2022-08-26
26-08-2022 00:00:00
2022-08-26 00:00:00
it seems that after the strftime function, the format is right, but when i call the strptime function, its getting back to the previous format "YY-mm-dd"
today = datetime.strptime(today, "%d-%m-%Y %H:%M:%S")
print (today)
That part is creating a datetime object.
You can do:
print (today.strftime("%d-%m-%Y %H:%M:%S"))
again in the final line
it seems that after the strftime function, the format is right, but when i call the strptime function, its getting back to the previous format "YY-mm-dd"
That is because print(today) determines the format since you didn't specify one. As other's pointed out, today is a datetime object. When you print() a datetime object, python will choose a format for you, I assume based on your system's locale settings.
One concept to understand here is the difference between a value and the representation of that value as a string. This is what formatting a datetime is for.
I suggest you don't worry about the output here too much. As long as your explicit format with strftime() gives you the correct representation, then you are good. This formatting should only be used for output. Otherwise, store datetimes and datetime objects in your variables.

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.

Python what is the correct timefomat for: 2018-11-13T20:20:39+00:00

I need to get a now() timestamp like this following: 2018-11-13T20:20:39+00:00 What is the correct format string for this?
To get an isoformat() string with time zone offset (the +00:00 at the end of the string) you need to supply a tzinfo object when constructing the datetime. the easiest way to do this is with the pytz library - pytz.timezone("UTC") returns the tzinfo for UTC.
There's another issue though, which is that technically that string doesn't quite match default isoformat() output because it has no microseconds. So a full example for the output requested would be:
import datetime
import pytz
datetime.datetime.now(tz=pytz.timezone("UTC")).replace(microsecond=0).isoformat()
This appears to be the isoformat.
You could use
import datetime as dt
# Get current time in utc
# Because the datetime object is timezone aware the +00:00 will be printed
current_time = dt.datetime.now(dt.timezone.utc)
# timespec will round the solution upto seconds
iso_string = current_time.isoformat(timespec="seconds")
print(iso_string)
will print 2019-11-19T19:51:46+00:00.

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

Python DateUtil Converting string to a date and time

I'm trying to convert a parameter of type string to a date time. I'm using the dateUtil library
from dateutil import parser
myDate_string="2001/9/1 12:00:03"
dt = parser.parse(myDate_string,dayfirst=True)
print dt
every time i run this i get
2001-09-01 12:00:03
regardless of whether i have dayfirst set as true or Year first set as false. Ideally I just want to have a date in the format DD-MM-YYYY HH:MM:SS. I don't want anything fancy. I am willing to use the datetime library but this doesn't seem to work at all for me. Can anyone give simple expamples of how to convert strings to date time with an explicit format, I'm a noob, so the most basic examples are all i require. I'm using Python 2.7
The problem you're having is that any arguments you pass to parser.parse only affect how the string is parsed, not how the subsequent object is printed.
parser.parse returns a datetime object - when you print it it will just use datetime's default __str__ method. If you replace your last line with
print dt.strftime("%d-%m-%Y %H:%M:%S")
it will work as you expect.
The standard lib (built-in) datetime lib can do this easily.
from datetime import datetime
my_date_string = "2001/9/1 12:00:03"
d = datetime.strptime(my_date_string, "%Y/%m/%d %H:%M:%S")
print d.strftime("%d-%m-%Y %H:%M:%S")

Categories

Resources