Python - Django project - DateTimeField format - python

I want to change the format of the Date in my Django project.
Now it looks like this: "June 3, 2018, 2:19 p.m.", and I want something like: "23,Oct 2018 - 18H23m".
The model that I have its setting this time:
date = models.DateTimeField(auto_now_add=True)
How can I format the date to the way I want? Are there any other parameters that allow me to do this?
I have just started working with django 2 days ago.
I tried to search around but didnt find any answer.

strftime() allows you to format datetimes as you like for printing etc:
import datetime
today = datetime.datetime.today()
print(today.strftime("%d, %b %Y - %HH%Mm"))
>>> 03, Jun 2018 - 16H54m

Try these following formats with strftime() that returns a string representing the date, controlled by an explicit format string of python. For a complete list of formatting directives: see this section
date = models.DateTimeField(auto_now_add=True)
>>> date.strftime("%d %b, %Y - %Ih%Mm%S %p") # With AM PM
>>> '03 Jun, 2018 - 12h02m49s PM'
>>> date.strftime("%d %b, %Y - %Hh%Mm")
>>> '03 Jun, 2018 - 12h04m'
You can use DATETIME_FORMAT = "d M Y H:i:s" in your settings to change the display format.

Related

How to compare date in python? I have a month date year format and want to compare to the current date (within 7 days)

This is the data that is being returned from my API:
"Jun 02, 2021, 2 PMEST"
If I'm within 7 days of the current date which I'm getting by doing this:
from datetime import date
today = date.today()
print("Today's date:", today)
Just need to convert Jun to a number and 02 and compare to see if it's within 7 days in the future of the current date, then return True
APPROACH 0:
Given the format of your example data, you should be able to convert it to a datetime using this code:
datetime.strptime("Jun 02, 2021, 2 PMEST", "%b %d, %Y, %I %p%Z")
The details about this format string are here: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
However, when I tested this locally, it worked for this input:
"Jun 02, 2021, 2 PMUTC"
but not for your input (which has different timezone):
"Jun 02, 2021, 2 PMEST"
I have investigated this some more and "read the docs" (https://docs.python.org/3/library/time.html).
To get EST parsing to work, you would have to change your OS timezone and reset the time module's timezones like this:
from datetime import datetime
import os
import time
os.environ["TZ"] = "US/Eastern". # change timezone
time.tzset(). # reset time.tzname tuple
datetime.strptime("Jun 02, 2021, 2 PMEST", "%b %d, %Y, %I %p%Z")
When you're done, be safe and delete the "hacked" environment variable:
del os.environ["TZ"]
Note - Since your system timezone is presumably still UTC, it can still parse UTC timezone too.
See this thread for detailed discussion: https://bugs.python.org/issue22377
Also note that the timestamp is not actually captured. The result you get with EST and UTC is a naive datetime object.
APPROACH 1
So, it seems like there is a better way to approach this.
First, you need to pip install dateutils if you don't already have it.
THen do something like this:
from dateutil import parser
from dateutil.tz import gettz
tzinfos = {"EST": gettz("US/Eastern")}
my_datetime = parser.parse("Jun 02, 2021, 2 PM EST", tzinfos=tzinfos)
What's happening here is we use gettz to get timezone information from the timezones listed in usr/share/zoneinfo. Then the parse function can (fuzzy) parse your string (no format needs to be specified!) and returns my_datetime which has timezone information on it. Here are the parser docs: https://dateutil.readthedocs.io/en/stable/parser.html
I don't know how many different timezones you need to deal with so the rest is up to you. Good luck.
Convert the date to a datetime structure and take the direct difference. Note that today must be a datetime, too.
import datetime
date_string = "Jun 02, 2021, 2 PMEST"
today = datetime.datetime.today()
date = datetime.datetime.strptime(date_string,
"%b %d, %Y, %I %p%Z") # Corrected
(date - today).days
#340

Python 3.7: converting a string with different timezone into date

I am trying to convert a string into date format in Python.
I am using following statement
datetime_obj = datetime.datetime.strptime("Sun Aug 19 16:24:31 PDT 2018", "%a %b %d %H:%M:%S %Z %Y")
However, I get an error -
ValueError: time data 'Sun Aug 19 16:24:31 PDT 2018' does not match format '%a %b %d %H:%M:%S %Z %Y'
If I remove the timezone from the date string and the format string, the code works perfect. Which leads me to believe that the issue is related to the timezone but I am not sure what actions should be taken.
I am in eastern timezone and the time zone in the string is in Pacific timezone.
Appreciate any help on this.
As mentioned in this answer you can use python-dateutil for this:
>>> from dateutil import parser
>>> datetime_obj = parser.parse("Sun Aug 19 16:24:31 PDT 2018")
datetime.datetime(2018, 8, 19, 16, 24, 31)
Standard datetime module behaves very strangely with parsing timezones, as I see reading this answer in question related to similar problem.

Python date time comparing with < return wrong result [duplicate]

This question already has answers here:
Parse CEST/CET time in python
(2 answers)
Closed 5 years ago.
I am creating simple RSS reader. Storing date of last read newest entry in newest_entry_datetime and then when reading again channel I am comparing entry time to newest_entry_datetime with < symbol as I read that Python is smart enough to recognize and compare datetime.
It works on the same day when time part is changing but on the next day newest date is implemented as old.
import datetime
import locale
#locale.setlocale(locale.LC_ALL, 'English_United States.1252')
newest_entry_datetime = 'Thu, 21 Dec 2017 16:02:03 CET'
entry_published = 'Fri, 22 Dec 2017 08:19:15 CET'
#dt_newest = datetime.datetime.strptime (newest_entry_datetime, "%a, %d %b %Y %H:%M:%S %Z" )
if (entry_published <= newest_entry_datetime):
print('Entry date is older')
else:
print('Entry date is NEW')
With such code I am getting result: "Entry date is older" which is wrong.
Second idea was to convert datestamps to datetime but I am getting:
ValueError: time data 'Thu, 21 Dec 2017 16:02:03 CET' does not match format '%a, %d %b %Y %H:%M:%S %Z'
even if I will change locale to US.
No clue how to do that correctly. Could you please help?
Thanks to Anton vBR answer that CET is not recognized I just removed this part of string as feed will always have the same timezone.
Final code that works and gives proper result is here.
import datetime
import locale
locale.setlocale(locale.LC_ALL, 'English_United States.1252')
newest_entry_datetime = 'Thu, 21 Dec 2017 16:02:03 CET'
entry_published = 'Fri, 22 Dec 2017 08:19:15 CET'
newest_entry_datetime = newest_entry_datetime.rsplit(" ", maxsplit=1)[0]
entry_published = entry_published.rsplit(" ", maxsplit=1)[0]
dt_newest = datetime.datetime.strptime (newest_entry_datetime, "%a, %d %b %Y %H:%M:%S" )
st_entry = datetime.datetime.strptime (entry_published, "%a, %d %b %Y %H:%M:%S" )
if (st_entry <= dt_newest):
print('Entry date is older')
else:
print('Entry date is NEW')
Result is: 'Entry date is NEW' as it was expected.
If you compare you "dates" before converting to datetime - you compare strings. First you need convert to datetime (use for it right format if current is not support you string datetime style), and after that you can compare two datetime objects.
You can't convert to datetime to this format because of 'CET', for timezones you can you custom desicion (like this).

Format Unicode time value

I have next time value in unicode (<type 'unicode'>):
2017-08-09T15:02:58+0000.
How to convert it to friendly view (e.g. Day, Month of Year)?
This should do what you ask:
from datetime import datetime
a = '2017-08-09T15:02:58+0000'
datetime.strptime(a[:-5], '%Y-%m-%dT%H:%M:%S').strftime('%d, %b of %Y')
#09, Aug of 2017
strptime method throws error for timezone parameter that doesn't seem to interest you so I removed that part with a[:-5].
For the rest of the string you can just follow guidelines from datetime docs.
Using the same docs you can construct your datetime string using strftime() method like you wanted '%d, %b of %Y' or in plain words [day], [abbreviated month] of [Year]
try this
import datetime
today = datetime.date.today()
print today.strftime('We are the %d, %b %Y')
'We are the 22, Nov 2008'

how to convert unix timestamp with z to date time in python

how would i convert this timestamp '20141031131429Z' to 31 october 2014 in python
>>>datetime.datetime.strptime( "20141031131429Z", "%Y%m%d%H%M%S%Z" )
the above code gives me an error shown below:
ValueError: time data '20141031131429Z' does not match format '%Y%m%d%H%M%S%Z'
Remove the % in front of the Z:
d = datetime.datetime.strptime("20141031131429Z", "%Y%m%d%H%M%SZ" )
print(d.strftime("%d %B %Y"))
Output:
31 October 2014
Set the documentation for the strftime() and strptime() behavior.
That's not a unix timestamp (which are parsed with %s in strftime/strptime) - it looks like iCalendar form #2 (RFC 2445). A module like iCalendar might help you parse that without having to hardcode which form is used.
Once you have a datetime object, it can be used to retrieve any other format:
>>> dt=datetime.datetime.strptime( "20141031131429Z", "%Y%m%d%H%M%SZ" )
>>> dt.strftime('%d %B %Y')
'31 October 2014'
>>> dt.strftime('%x')
'10/31/14'

Categories

Resources