python change Jun to June - python

I take the tomorrows date like this
tomorrow = datetime.date.today() + datetime.timedelta(days=1)
self.FirstDateString = str(tomorrow.strftime("%d %b %Y"))
and the result is 11 Jun 2014
I parse it like this:
datetime.strptime('11 Jun 2014', "%d %B %Y").date()
I got this error:
ValueError: time data '11 Jun 2014' does not match format '%d %B %Y'
but when I change Jun to June, it works.
So, how can I tell the tomorrow = datetime.date.today() + datetime.timedelta(days=1) to give me June instead of Jun
in my case I will have both Jun and June so I would prefer to change Jun to June to make everything works

I think I understand the issue. You don't need to convert the datetime object to a string first:
import datetime
today = datetime.datetime.today()
print(datetime.datetime.strftime(today, '%d %b %Y'))
print(datetime.datetime.strftime(today, '%d %B %Y'))
This will give you:
10 Jun 2014
10 June 2014
Now, if your problem is that you have some strings and want to convert them, but some have Jun and others June, you don't have a choice but to try it one way, and if it doesn't work, try it the other way:
try:
obj = datetime.datetime.strptime(some_string, '%d %b %Y')
except ValueError:
# It didn't work with %b, try with %B
try:
obj = datetime.datetime.strptime(some_string, '%d %B %Y')
except ValueError:
# Its not Jun or June, eeek!
raise ValueError("Date format doesn't match!")
print('The date is: {0.day} {0.month} {0.year}'.format(obj))

You need to use the %b format code for abbreviated month names:
>>> from datetime import datetime
>>>
>>> datetime.strptime('11 Jun 2014', "%d %B %Y").date()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python33\lib\_strptime.py", line 500, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "C:\Python33\lib\_strptime.py", line 337, in _strptime
(data_string, format))
ValueError: time data '11 Jun 2014' does not match format '%d %B %Y'
>>>
>>> datetime.strptime('11 Jun 2014', "%d %b %Y").date()
datetime.date(2014, 6, 11)
>>>

Related

How to convert UTC/extended format to datetime in Python

I want to convert datetime in %Y-%m-%d,
so from Sat, 17 Apr 2021 16:17:00 +0100 to 17-04-2021
def convertDatetime(data):
test_datetime = data
data_new_format = datetime.datetime.strptime(test_datetime,'%- %Y %M %d')
print(data_new_format)
convertDatetime("Sat, 17 Apr 2021 16:17:00 +0100")
but it say me: '-' is a bad directive in format '%- %Y %M %d'
The format you specify '%- %Y %M %d' (1) contains an incorrect specifier - as the error says, and also (2) completely does not match the data you want to convert. The format you pass to strptime() must match the way the data looks, not the way you want it to look.
>>> data="Sat, 17 Apr 2021 16:17:00 +0100"
>>> format = "%a, %d %b %Y %H:%M:%S %z"
>>> datetime.datetime.strptime(data, format)
datetime.datetime(2021, 4, 17, 16, 17, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600)))
To reformat the datetime the way you want, you need a second call, to strftime():
>>> datetime.datetime.strptime(data, format).strftime("%Y-%m-%d")
'2021-04-17'

Convert date string (from gmail) to timestamp | Python

I want to save the received date of emails from a Gmail account into a time-series database.
The problem is that I cannot convert the string that I got from the email to timestamp.
I tried this:
from datetime import datetime
date1 = 'Thu, 28 May 2020 08:15:58 -0700 (PDT)'
date1_obj = datetime.strptime(date1, '%a, %d %b %Y %H:%M:%S %z %Z')
print(date1_obj)
But got this error:
Traceback (most recent call last):
File "/format_date.py", line 11, in <module>
date1_obj = datetime.strptime(date1, '%a, %d %b %Y %H:%M:%S %z %Z')
File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_strptime.py", line 577, in _strptime_datetime
tt, fraction, gmtoff_fraction = _strptime(data_string, format)
File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_strptime.py", line 359, in _strptime
(data_string, format))
ValueError: time data 'Thu, 28 May 2020 08:15:58 -0700 (PDT)' does not match format '%a, %d %b %Y %H:%M:%S %z %Z'
Tried with or without parenthesis wrapping Timezone.
Read a lot, but nothing about how to deal with date strings containing "(PDT)" or any other timezones. It's very important to get the right date... If I run the same code without "(PDT)", got an incorrect time (because of my local time).
I know I can use string methods to manipulate it and convert to a right datetime, but I feel like this would be flexible.
Sorry for my terrible English.
Thank you!
you could use dateutil's parser to parse the string, automatically inferring the format:
import dateutil
s = 'Thu, 28 May 2020 08:15:58 -0700 (PDT)'
dt = dateutil.parser.parse(s)
# datetime.datetime(2020, 5, 28, 8, 15, 58, tzinfo=tzoffset('PDT', -25200))
dt.utcoffset().total_seconds()
# -25200.0
Note that although the timezone is given a name ("PDT"), it is only a UTC offset of 25200 s. In many cases that is sufficient, at least to convert to UTC.
If you need the specific timezone (e.g. to account for DST transitions etc.), you can use a mapping dict that you supply to dateutil.parser.parse as tzinfos:
tzmap = {'PDT': dateutil.tz.gettz('US/Pacific'),
'PST': dateutil.tz.gettz('US/Pacific')}
dt = dateutil.parser.parse(s, tzinfos=tzmap)
# datetime.datetime(2020, 5, 28, 8, 15, 58, tzinfo=tzfile('US/Pacific'))
dt.utcoffset().total_seconds()
# -25200.0
Close, you forgot to put the bracket around the last entry.
date1_obj = datetime.strptime(date1, '%a, %d %b %Y %H:%M:%S %z (%Z)')
Well, after all your answers, which were very helpful, I finally solved.
This is how:
>>> from email.utils import parsedate_tz, mktime_tz
>>> date = 'Thu, 28 May 2020 08:15:58 -0700 (PST)'
>>> timestamp = mktime_tz(parsedate_tz(date))
>>> timestamp
1590678958
>>>
I checked that timestamp, and stands to 12:15:58 local time, what it's exactly what I was looking for.
Thank you very much to everybody who took a minute to answer.
If it does not work even if you enclose %Z in brackets then the problem lies within the %Z directive
https://docs.python.org/3/library/time.html
Support for the %Z directive is based on the values contained in
tzname and whether daylight is true. Because of this, it is
platform-specific except for recognizing UTC and GMT which are always
known (and are considered to be non-daylight savings timezones).
In example the following results in a ValueError for me (in Europe)
date1 = 'Thu, 28 May 2020 08:15:58 -0700 (PST)'
date1_obj = datetime.strptime(date1, '%a, %d %b %Y %H:%M:%S %z (%Z)')
print(date1_obj)
While with GMT it the output is 2020-05-28 08:15:58-07:00
date1 = 'Thu, 28 May 2020 08:15:58 -0700 (GMT)'
date1_obj = datetime.strptime(date1, '%a, %d %b %Y %H:%M:%S %z (%Z)')
print(date1_obj)
Based on your comment under this answer you could split the string if the Timezone bit is not important:
date1 = 'Thu, 28 May 2020 08:15:58 -0700 (GMT)'
date1_obj = datetime.strptime(date1.split(" (")[0], '%a, %d %b %Y %H:%M:%S %z')

Parsing GST timezone with datetime.strptime

I am trying to parse a str as a datetime.datetime object. However, I am unable to achieve this because the timezone is GST.
import datetime
s_dt = 'Mon Jul 01 17:17:37 UTC'
datetime.datetime.strptime(s_dt, '%a %b %d %H:%M:%S %Z')
# datetime.datetime(1900, 7, 1, 17, 17, 37)
s_dt = 'Mon Jul 01 17:17:37 GST'
datetime.datetime.strptime(s_dt, '%a %b %d %H:%M:%S %Z')
# ValueError: time data 'Mon Jul 01 17:17:37 GST' does not match format '%a %b %d %H:%M:%S %Z'
How can I fix this?
There are two ways to deal with this:-
Replace the GST in the string, to UTC
Replace the GST in the string, to UTC with proper time conversion (decreasing the time in UTC by 4 hours, as time GST is +4 hours from UTC).
METHOD 1:-
s_dt = 'Mon Jul 01 17:17:37 GST'.replace("GST", "UTC")
datetime.datetime.strptime(s_dt, '%a %b %d %H:%M:%S %Z')
METHOD 2:-
# replacing GST to UTC in original string
s_dt = 'Mon Jul 01 17:17:37 GST'.replace("GST", "UTC")
# getting the hours from the string
s_dt_obj = int(s_dt.split(":")[0][-2:])
# substracting 4 from the hours (in order to create UTC equivalent of GST time)
s_dt_obj = str((s_dt_obj - 4) % 24)
# putting everything back to a string
s_dt_obj = f"{s_dt.split(':')[0][:-2]}{s_dt_obj}:{s_dt.split(':')[1]}:{s_dt.split(':')[2]}"
# creating datetime object out of our newly created string
datetime.datetime.strptime(s_dt_obj, '%a %b %d %H:%M:%S %Z')
# datetime.datetime(1900, 7, 1, 13, 17, 37)

ValueError: time data '13 Aug 05' does not match format '%d %m %y'

Not sure why I'm getting this error when trying to parse a string into datetime.
This is the code I have:
date = datetime.strptime("13 Aug 05", '%d %m %y')
and it is raising this error:
ValueError: time data '13 Aug 05' does not match format '%d %m %y'
date = datetime.strptime("13 Aug 05", '%d %b %y')
You need to use %b, not %m, because your string uses the month's 3-letter abbreviated name and not the zero-padded decimal number.

Cannot parse the date in Python

I need to parse date and time. Here is what I've got:
import time
a = time.strptime('Apr 28 2013 23:01', "%b %d %y %H:%M")
print a
But it gives me
Traceback (most recent call last):
File "/home/aaa/Documents/python_test.py", line 17, in <module>
a = time.strptime('Apr 28 2013 23:01', "%b %d %y %H:%M")
File "/usr/lib/python2.7/_strptime.py", line 467, in _strptime_time
return _strptime(data_string, format)[0]
File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data 'Apr 28 2013 23:01' does not match format '%b %d %y %H:%M'
What am I doing wrong?
%y should be %Y for a 4 digit year...
From the docs:
%y Year without century as a decimal number [00,99].
%Y Year with century as a decimal number.
You can
import time
a = time.strptime('Apr 28 2013 23:01', "%b %d %Y %H:%M")
print time.strftime("%d/%m/%Y",a)
with Y. It is followed by a conversion line of code, and gives result
28/04/2013
Jon's answer is of course correct, but as you noticed these things can be difficult to find.
As a general suggestion for debugging strptime problems I recommend printing out a known datetime using the format string you use for parsing:
from datetime import datetime
d = datetime(2013, 4, 28, 23, 1)
print d.strftime("%b %d %y %H:%M")
print 'Apr 28 2013 23:01'
A visual comparison of the output lines:
Apr 28 13 23:01
Apr 28 2013 23:01
quickly finds the problem and also works when your format string is correct, but you are working with a different locale (e.g. in Spanish where it would expect 'Abr' instead of 'Apr')

Categories