datetime to date format in python - python

I Have a value of
datetime.datetime(2015, 1, 28, 13, 53, 36)
and I want it to be printed as string as
Wednesday, January 28, 2015 13:53:36
I tried to
import datetime
x = datetime.datetime(2015, 1, 28, 13, 53, 36)
z = strptime(str(x), '%A, %B %d, %Y %H:%M:%S')
but got:
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
z = strptime(str(x), '%A, %B %d, %Y %H:%M:%S')
NameError: name 'strptime' is not defined
does anyone have an idea about this?

Given your import - the correct form of accessing strptime is datetime.datetime.strptime (parsing a string to a date) - but it doesn't look like you want that, instead you're after datetime.datetime.strftime (formats a date to a string).
Ultimately though, Python's datetime object has custom string formatting which can be accessed via str.format and will save a bit of typing, eg:
>>> dt = datetime.datetime(2015, 1, 28, 13, 53, 36)
>>> format(dt, '%A, %B %d, %Y %H:%M:%S')
'Wednesday, January 28, 2015 13:53:36'

Use the date method:
datetime.datetime.date()
You should use datetime.datetime.strptime:
import datetime
dt = datetime.datetime.strptime(string_date, fmt)

Related

Correct format for converting french date from string to datetime?

I'm trying to convert strings to date, but it's not working for some dates in french. Like in the example below :
myDate = datetime.strptime(dateInStringFormat, "%A %d %B %Y %H:%M:%S")
Result with the error : time data '"jeudi 8 septembre 2022 13:51:13"' does not match format '%A %d %B %Y %H:%M:%S'.
I've tried a lot a variations in the format I can't make it work, anyone know how to do this please ?
try:
import locale
import datetime
locale.setlocale(locale.LC_ALL, 'fr_FR.UTF-8')
dateInStringFormat = "jeudi 8 septembre 2022 13:51:13"
myDate = datetime.datetime.strptime(dateInStringFormat, "%A %d %B %Y %H:%M:%S")
print(myDate)
# 2022-09-08 13:51:13
myDate
# datetime.datetime(2022, 9, 8, 13, 51, 13)
I had the same problem once and found a module called dateparser to do that:
import dateparser
d = dateparser.parse("jeudi 8 septembre 2022 13:51:13")
d is now
datetime.datetime(2022, 9, 8, 13, 51, 13)

datetime.strptime Format does not match format '%d. %B %Y'

I want to convert type of string date to other format which as dd-mm-yyyy
date_stringg='24. Juli 2020'
date_object = datetime.strptime((date_stringg), "%d. %B %Y")
print("date_object: ", date_object)
You may need to set the locale. Juli is not a valid month name in english language, I'm assuming it is Dutch.
Assuming you want to use the Dutch locale with datetime, you can do the following
import locale
locale.setlocale(locale.LC_TIME, "nl_nl")
After that, it will recognize Juli so this will work
>>> date_stringg='24. Juli 2020'
>>>
>>> date_object = datetime.strptime((date_stringg), "%d. %B %Y")
>>> date_object
datetime.datetime(2020, 7, 24, 0, 0)
This looks like a locale setting problem. See the example below:
>>> locale.setlocale(locale.LC_ALL, 'C')
'C'
>>> datetime.datetime.strptime('24. Julho 2020', '%d. %B %Y')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.8/_strptime.py", line 568, in _strptime_datetime
tt, fraction, gmtoff_fraction = _strptime(data_string, format)
File "/usr/local/lib/python3.8/_strptime.py", line 349, in _strptime
raise ValueError("time data %r does not match format %r" %
ValueError: time data '24. Julho 2020' does not match format '%d. %B %Y'
>>> locale.setlocale(locale.LC_ALL, 'pt_PT.utf8')
'pt_PT.utf8'
>>> datetime.datetime.strptime('24. Julho 2020', '%d. %B %Y')
datetime.datetime(2020, 7, 24, 0, 0)
You may need to select (and maybe install/configure your underlying system) for the language you are using in the strings you want to parse.
In the example you see I wrote the string 'Julho' (July) in Portuguese, so the proper locale has to be active.
See also the Python documentation on setting the locale

How to parse a string like '2016-08-01 13:39:00+05:30' into datetime object of python

I am getting below error while trying to do this
from datetime import datetime
time1 = '2016-08-01 13:39:00+05:30'
x = datetime.strptime(time1, '%Y-%m-%d %H:%M:%S %z')
print(x)
Error is ...
ValueError: time data '2016-08-01 13:39:00+05:30' does not match format '%Y-%m-%d %H:%M:%S %z'
If you are using Python 2 or early versions of Python 3 (3.0 and 3.1), you can use the dateutil library for converting a string to a timezone aware object.
The code to do this is simple:
>>> import dateutil.parser
>>> dt = dateutil.parser.parse('2016-08-01 13:39:00+05:30')
>>> dt
datetime.datetime(2016, 8, 1, 13, 39, tzinfo=tzoffset(None, 19800))
If you are using Python 3.2 or later, the %z option has been added as a formatting option when parsing a date. You can accomplish this task without using dateutil in these versions by doing this:
>>> import datetime
>>> dt = datetime.datetime.strptime('2016-08-01 13:39:00+0530', "%Y-%m-%d %H:%M:%S%z")
>>> dt
datetime.datetime(2016, 8, 1, 13, 39, tzinfo=datetime.timezone(datetime.timedelta(0, 19800)))
Unfortunately, you do have to strip the colon (:) from the offset for this to work as expected.
this works in python 3.4, conforms to the datetime documentation
from datetime import datetime
time1 = '2016-08-01 13:39:00+0530'
x = datetime.strptime(time1, '%Y-%m-%d %H:%M:%S%z')
print(x)
gives
2016-08-01 13:39:00+05:30
Consider using dateparser:
>>> dateparser.parse('2016-08-01 13:39:00+05:30')
datetime.datetime(2016, 8, 1, 13, 39)
>>> dateparser.parse('2016-08-01 13:39:00+05:30', settings={'TO_TIMEZONE': 'UTC'})
datetime.datetime(2016, 8, 1, 8, 9)

Converting localized string date representation to UTC in python

How do I convert the following localized datetime string to UTC datetime. The string has date, time and timezone mentioned in it e.g. May 15,2015, 04.24AM IST, here IST is Indian Standard Time. It can be any time zone.
I tried using pytz but couldn't make it work.
The thing is that it's quite difficult to parse a string with an abbreviated timezone information. But, if you know your timezone, then you can look up it's name recognized by pytz. You can even list all timezone names with pytz.all_timezones.
In your case it is 'Asia/Calcutta' and this should work to convert it to UTC. Just strip the timezone information from the string and add it later:
import pytz
import datetime
# String without timezone info
str = "May 15, 2015, 04.24AM"
# Parse it to naive time
dt = datetime.datetime.strptime(str, "%b %d, %Y, %I.%M%p")
# Localize it as Asia/Calcutta
dt_localized = pytz.timezone('Asia/Calcutta').localize(dt)
# Convert it to UTC
dt_utc = dt_localized.astimezone(pytz.timezone('UTC'))
And we get:
>>> dt
datetime.datetime(2015, 5, 15, 4, 24)
>>> dt_localized
datetime.datetime(2015, 5, 15, 4, 24, tzinfo=<DstTzInfo 'Asia/Calcutta' IST+5:30:00 STD>)
>>> dt_utc
datetime.datetime(2015, 5, 14, 22, 54, tzinfo=<UTC>)
First, let's strip your date string of the IST timezone and then assign it the Asia/Calcutta timezone.
import pytz
dt_str = "May 15, 2015, 04.24AM IST"
dt_str_naive = dt_str[:-4]
new_dt = (pytz.timezone('Asia/Calcutta')
.localize(dt.datetime.strptime(dt_str_naive, "%b %d, %Y, %I.%M%p")))
Now that it is timezone aware, you can assign it to the UTC timezone:
>>> new_dt.astimezone(pytz.UTC)
datetime.datetime(2015, 5, 14, 22, 54, tzinfo=<UTC>)

Why doesn't my Python code accept %z as a DateTime directive?

I'm trying to parse the following string into a valid datetime format:
Wed, 10 Sep 2014 11:20:58 +0000
for which I use this Python code:
dtObject = datetime.strptime(e[attr], '%a, %d %b %Y %H:%M:%S %z')
Unfortunately I get an error saying:
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 317, in _str
ptime
(bad_directive, format))
ValueError: 'z' is a bad directive in format '%a, %d %b %Y %H:%M:%S %z'
According to the strptime() docs, %z should be totally correct for UTC offset in the form +HHMM or -HHMM.
Does anybody know what I'm doing wrong here? All tips are welcome
It looks as if strptime doesn't always support %z (see this answer)
Instead of strptime, you can use dateutil.parser and it works fine:
>>> import dateutil.parser
>>> s='Wed, 10 Sep 2014 11:20:58 +0000' #UTC
>>> dateutil.parser.parse(s)
datetime.datetime(2014, 9, 10, 11, 20, 58, tzinfo=tzutc())
>>> s='Wed, 10 Sep 2014 11:20:58 +0100' #ANOTHER TZ
>>> dateutil.parser.parse(s)
datetime.datetime(2014, 9, 10, 11, 20, 58, tzinfo=tzoffset(None, 3600))

Categories