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'
Related
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
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.
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).
If I have the following timestring:
20150505
How would I convert this into the date May 5, 2015 in Python? So far I've tried:
from datetime import datetime
sd = datetime.strptime('20150504', '%Y%M%d')
But this outputs:
2015-01-04 00:05:00
The capital M denotes minute not month. Use the lowercase m and then call the strftime method to refactor the format:
>>> datetime.strptime('20150504', '%Y%m%d').strftime('%b %d, %Y')
'May 04, 2015'
You can remove the zero padding from the month by using the -d directive in place of d:
%-d Day of the month as a decimal number. (Platform specific)
For longer month names, you can use the directive %B in place of %b to get the full month name.
Reference:
http://strftime.org/
If you know it's a date and not a datetime, or you don't know the format. You can use dateutil.
from dateutil.parser import parse
print(parse('20150504'))
This is the anwser, wihout leading zero for day, as OP's example:
print(sd.strftime('%b %-d, %Y'))
# Jan 4, 2015 # note your sd parsing is wrong. Thus Jan
A variety of programs output date formats according to the syntax of their Unix platforms date command. For example: Tue Nov 5 12:38:00 EST 2013.
How can I easily convert this into a Python date object?
The answer is actually pretty simple. You just need to use the datetime.strptime() method which converts a string representation of a date (1st parameter) into a date object based on a directive which specifies that format of the string representation (2nd parameter).
In this case, this is the code you would use:
import datetime
unix_date_format = '%a %b %d %H:%M:%S %Z %Y'
# Matches strings like Tue Nov 5 12:38:00 EST 2013
my_date = datetime.datetime.strptime(
date_in_string_format, unix_date_format)
Further Reading
datetime.strptime() method