Python DateUtil Converting string to a date and time - python

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

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: How to display date time in following format (2018-06-25T07:17:17.000Z)?

I want to display the datetime in the following format using python:
2018-06-25T07:17:17.000Z
I am trying to convert using strftime:
datetime.datetime.now().strftime("%Y-%m-%dTH:M:SZ")
but it seems that doesn't work.
What i am missing?
you can use
import datetime
datetime.datetime.today().isoformat()
2018-06-25T07:17:17.000Z
This format is called ISO format, after standard ISO 8601. The datetime object has a isoformat method to output this form.
strftime("%Y-%m-%dTH:M:SZ")
You seem to have forgotten some % before the H, M, and S. Try strftime("%Y-%m-%dT%H:%M:%SZ").
but it seems that doesn't work.
Generally it works better if you specify exactly what doesn't work, or what you expect and how the reality differs from your expectation.
You can use following formating for date conversion.
>>> import datetime
>>> today_date = datetime.datetime.now()
>>> today_date.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
'2018-06-25T15:50:18.313620Z'
Please let me know,if this is the one you needed.

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

set default datetime format in python

How to set default datetime format in python because i have multiple tuples to send via template on client side. This is not good approach to set each object's value to specified format. I want to set a datetime format on server side and these converted values will be shown to client. I tried
datetime.strftime("%Y-%m-%d %X")
but it is giving error.
strftime is a method of datetime objects - it doesn't set a default representation, which seems to be what you suggest. For example, you might call it like this:
>>> import datetime
>>> now = datetime.datetime.now()
>>> now.strftime("%Y-%m-%d %X")
'2011-03-17 10:14:12'
If you need to do this a lot, it would be worth creating a method that wraps this conversion of a datetime to a string. The documentation for the datetime module can be found here.
I'm not sure I understand your issue, but this might help
http://docs.djangoproject.com/en/dev/ref/settings/
there is a datetime format section, this sets datetime format globally.

Categories

Resources