Extracting just the year, month and day from this format - python

If I have a dict with date formatted as 'Thu May 01 04:19:08 +0000 2014' how do I go about extracting just the Year, Month and Day to a variable so that I can then search via date range. I need it in '%Y %M %D' '%H %M %S' using python.

You can use datetime.datetime.strptime to parse that string into a date object and then use strftime (strftime for format, strptime for parse) to extract it in your desired format.
import datetime
date = "Thu May 01 04:19:08 +0000 2014"
objectified = datetime.datetime.strptime(date, "%a %b %d %H:%M:%S %z %Y")
formatted = objectified.strftime("'%Y %M %D' '%H %M %S'")
>>> formatted
"'2014 19 05/01/14' '04 19 08'"
Placeholders are explained here

Related

How can I convert datetime to unix timestamp in python

I have one date format "Mon, 15 Jun 2020 22:11:06 PT" I want to convert this format to unix timestamp.
I am using the following code ===>
news_date = datetime.strptime(news_date, '%a, %d %b %Y %H:%M:%S %Z')
news_date = calendar.timegm(news_date.utctimetuple())
But gives the following error ===>
ValueError: time data 'Mon, 15 Jun 2020 22:11:06 PT' does not match format '%a, %d %b %Y %H:%M:%S %Z'
How can i solve it and get the unix timestamp from this?
%Z can't parse the timezone name PT - I suggest you skip parsing it and add it "manually" instead:
from datetime import datetime
import dateutil
news_date = "Mon, 15 Jun 2020 22:11:06 PT"
# parse string without the timezone:
news_date = datetime.strptime(news_date[:-3], '%a, %d %b %Y %H:%M:%S')
# add the timezone:
news_date = news_date.replace(tzinfo=dateutil.tz.gettz('US/Pacific'))
# extract POSIX (seconds since epoch):
news_date_posix = news_date.timestamp()
# 1592284266.0
if you have multiple strings with different timezones, you could use a dict to map the abbreviations to time zone names, e.g.
tzmapping = {'PT': 'US/Pacific'}
news_date = "Mon, 15 Jun 2020 22:11:06 PT"
# get appropriate timezone from string, according to tzmapping:
tz = dateutil.tz.gettz(tzmapping[news_date.split(' ')[-1]])
# parse string and add timezone:
news_date_datetime = datetime.strptime(news_date[:-3], '%a, %d %b %Y %H:%M:%S')
news_date_datetime = news_date_datetime.replace(tzinfo=tz)

How to strip date time in python

From a website I'm getting a date in such format: Sun Jan 22 21:32:58 +0000 2012. I understand that I must get rid of +0000 to convert it to the date, but how exactly I can do it? I read the documentation but my code is not working:
from datetime import datetime
strDate = 'Mon Apr 29 14:30:53 2019'
objDate = datetime.strptime(strDate, '%a %b %H %M %S %Y')
I'm getting an error:
ValueError: time data 'Mon Apr 29 14:30:53 2019' does not match format '%d %m %H %M %S %Y'
And I don't really understand why. Or anyone knows how I can get a date from Sun Jan 22 21:32:58 +0000 2012?
If your object is datetime.datetime you can just simply do date()
from datetime import datetime
datetime1 = datetime.now()
date1 = datetime1.date()
One line solution:
strDate ='Sun Jan 22 21:32:58 +0000 2012'
objDate = datetime.strptime(strDate, '%a %b %d %H:%M:%S +%f %Y')
print(objDate)
#2019-04-29 14:30:53
Details:
You just forgot to use %d in order to capture the date number and the : for the time and you ALSO need to capture +0000.
Proof:
I'm afraid that the currently accepted answer, by seralouk, is incorrect. Using "+%f" turns the numbers into fractions of seconds. It's fine for 0000, but will mess things up if they happen to be anything else.
This is because the "+0000" part is a time zone offset, and the proper way to parse it is by using the "%z" directive, which will handle the "+" sign as well, so remove that from the format string:
>>> date_string = "Sun Jan 22 21:32:58 +0000 2012"
>>> datetime.strptime(date_string, "%a %b %d %H:%M:%S %z %Y")
datetime.datetime(2012, 1, 22, 21, 32, 58, tzinfo=datetime.timezone.utc)
You're missing colons : and the day format string %d. See the official documentation of strptime for a table that shows the different formatting values.
from datetime import datetime
strDate = 'Mon Apr 29 14:30:53 2019'
objDate = datetime.strptime(strDate, '%a %b %d %H:%M:%S %Y')
You can get rid of the '+0000' like this:
from datetime import datetime
strDate ='Sun Jan 22 21:32:58 +0000 2012'
objDate = datetime.strptime(strDate.replace(strDate.split(" ")[4] + " ", ""), '%a %b %d %H:%M:%S %Y')
print(objDate)
-> 2012-01-22 21:32:58
By the way,
1. The example of code that you post is not the one for the problem that you are asking about! (it does not include the +0000 in the string).
2. The error that you share (false format of the date, which has been answered already and described f.ex. here) is for another code, not the one you present above! (Error throws '%d %m %H %M %S %Y' instead of '%a %b %H %M %S %Y').
In your string u are missing the %d to catch the Day of month 01-31
'%a %b %d %H:%M:%S %Y'
If u want also to catch the +0000 u have to use the %z notation
Use this as a refrence to build your string correctly:
http://strftime.org/

Converting from unix time string to python date type, Does not convert when CDT is present

I have a date time string in this format in python
"Wed Mar 20 00:52:54 CDT 2019 20 Mar 2019"
I am trying to convert this to python date time format using below code
datetime.datetime.strptime('Wed Mar 20 00:52:54 CDT 2019', "%a %b %d %H:%M:%S %Y")
But it gives error as CDT is present in the text. How to handle this problem. I am not sure if CDT will be present for all dates. In both cases i want to convert.
My requirement is only to get the difference in days between this date and now
Use CDT in the format, then calculate the difference between now and that date. Finally print delta.days.
from datetime import datetime
date0 = datetime.strptime('Wed Mar 20 00:52:54 CDT 2019', "%a %b %d %H:%M:%S CDT %Y")
date_now = datetime.now()
delta = date_now - date0
print(delta.days)
Output in this case:
0
If you're not sure if there will be CDT, check the string before passing it to strptime. Or use try/except:
try:
date0 = datetime.strptime(string, "%a %b %d %H:%M:%S CDT %Y")
except ValueError:
date0 = datetime.strptime(string, "%a %b %d %H:%M:%S %Y")

Python Given a date, time, hour... how can i get it's formated ISO ZULU

I have been using python IMAP protocol and I read email headers and retrieve the Date which looks like
myDate --> Fri, 22 Feb 2019 17:00:06 +0000
I need to find the equivalent UTC ISO8601 with zulu formatting how can I do that?
I tried:
dateInUTCIso= datetime.datetime.strptime(myDate, '%a, %d %b %Y %H:%M:%S +%f').date().isoformat()
but I am only getting year/month/date
dateInUTCIso= 2019-02-22
Remove the .date() method call
myDate = "Fri, 22 Feb 2019 17:00:06 +0000"
dateInUTCIso= datetime.datetime.strptime(myDate, '%a, %d %b %Y %H:%M:%S +%f').isoformat() + 'Z'
# 2019-02-22T17:00:06Z
You're calling .date().isoformat(). Without .date() you would get the ISO format.
However, if you want Z instead of +00:00 at the end, you'll have to swap out that part after the fact with .replace('+00:00', 'Z') on the string output

How convert this string to iso 8601 with Python

I have this string
14 Mai 2014
I want to convert it to iso 8601
i read this answer and this one,
and first i try to convert string to date and then in i convert it to iso format:
test_date = datetime.strptime("14 Mai 2014", '%d %m %Y')
iso_date = test_date.isoformat()
i got this error:
ValueError: time data '14 Mai 2014' does not match format '%d %m %Y'
According to Python strftime reference %m means day of month and in your case "Mai" seems to be name of month in your current locale and you have to use this %b format. So your piece of code should looks like this:
test_date = datetime.strptime("14 Mai 2014", '%d %b %Y')
iso_date = test_date.isoformat()
And don't forget to set locale.
For English locale it works:
>>> from datetime import datetime
>>> test_date = datetime.strptime("14 May 2014", '%d %b %Y')
>>> print(test_date.isoformat())
2014-05-14T00:00:00
You need to use %b token instead of %m.
And for use %b token you must set a locale.
Python Documentation
import datetime
import locale
locale.setlocale(locale.LC_ALL, 'fr_FR')
test_date = datetime.datetime.strptime("14 Mai 2014", '%d %b %Y')
iso_date = test_date.isoformat()
The result will be '2014-05-14T00:00:00'

Categories

Resources