Hello I am trying to convert a string which is a = "2019-04-22 00:00" to a datetime but it does not work, I tried this :
a = datetime.datetime.strptime(a, '%Y-%m-%d %H:%M')
But I got
time data 'start_period' does not match format '%Y-%m-%d %H:%M'
I precise start_period is get by this : a = request.POST.get('start_period')
Like this it should work:
import datetime
start_period = "2019-04-22 00:00"
a = datetime.datetime.strptime(start_period, '%Y-%m-%d %H:%M')
Result:
datetime.datetime(2019, 4, 22, 0, 0)
May I suggest using dateutil module, where you do not need to provide the format string
from dateutil import parser
print(parser.parse("2019-04-22 00:00"))
#2019-04-22 00:00:00
there are multiple ways to convert string to datetime in python. it is based on the requirement of the user which function to use.
one possible solution could be as given below.
import timestring
start_period = "2019-04-22 00:00"
print(timestring.Date(start_period))
Related
I'm trying to format a date to a customized one. When I use datetime.datetime.now(), I get the right format of date I'm after. However, my intention is to get the same format when I use 1980-01-22 instead of now.
import datetime
date_string = "1980-01-22"
item = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
print(item)
Output I get:
2021-05-04T09:52:04.010Z
How can I get the same format of date when I use a customized date, as in 1980-01-22 instead of now?
MrFuppes suggestion in the comments is the shortest way to accomplish your date conversion and formatting use case.
Another way is to use the Python module dateutil. This module has a lot of flexibility and I use it all the time.
Using dateutil.parser.parse:
from dateutil.parser import parse
# ISO FORMAT
ISO_FORMAT_MICROS = "%Y-%m-%dT%H:%M:%S.%f%z"
# note the format of these strings
date_strings = ["1980-01-22",
"01-22-1980",
"January 22, 1980",
"1980 January 22"]
for date_string in date_strings:
dt = parse(date_string).strftime(ISO_FORMAT_MICROS)
# strip 3 milliseconds for the output and add the ZULU time zone designator
iso_formatted_date = f'{dt[:-3]}Z'
print(iso_formatted_date)
# output
1980-01-22T00:00:00.000Z
1980-01-22T00:00:00.000Z
1980-01-22T00:00:00.000Z
1980-01-22T00:00:00.000Z
Using dateutil.parser.isoparse:
from dateutil.parser import isoparse
from dateutil.tz import *
dt = isoparse("1980-01-22").isoformat(timespec="milliseconds")
iso_formatted_date = f'{dt}Z'
print(iso_formatted_date)
# output
1980-01-22T00:00:00.000Z
Is this what your trying to achieve?
date_string = "1980-01-22"
datetime.datetime.strptime(date_string, "%Y-%m-%d").isoformat(timespec="milliseconds")
Output
'1980-01-22T00:00:00.000'
I am trying to parse this string:
string_date = "2020-10-06T12:31:15-05:00"
dt = datetime.datetime.strptime(string_date, '%Y-%m-%d %H:%M:%S %Z')
But, it doesn't work. However, I am not sure how to properly put this into a datetime object. How would I do this?
Your:
string_date = "2020-10-06T12:31:15-05:00"
seems like ISO format for me, so I did:
import datetime
string_date = "2020-10-06T12:31:15-05:00"
dt = datetime.datetime.fromisoformat(string_date)
print(dt)
print(dt.tzinfo)
Output:
2020-10-06 12:31:15-05:00
UTC-05:00
Is above what are you looking for?
How can one make 2020/09/06 15:59:04 out of 06-09-202015u59m04s.
This is my code:
my_time = '06-09-202014u59m04s'
date_object = datetime.datetime.strptime(my_time, '%d-%m-%YT%H:%M:%S')
print(date_object)
This is the error I receive:
ValueError: time data '06-09-202014u59m04s' does not match format '%d-%m-%YT%H:%M:%S'
>>> from datetime import datetime
>>> my_time = '06-09-202014u59m04s'
>>> dt_obj = datetime.strptime(my_time,'%d-%m-%Y%Hu%Mm%Ss')
Now you need to do some format changes to get the answer as the datetime object always prints itself with : so you can do any one of the following:
Either get a new format using strftime:
>>> dt_obj.strftime('%Y/%m/%d %H:%M:%S')
'2020/09/06 14:59:04'
Or you can simply use .replace() by converting datetime object to str:
>>> str(dt_obj).replace('-','/')
'2020/09/06 14:59:04'
As your error says what you give does not match format - %d-%m-%YT%H:%M:%S - means you are expecting after year: letter T hour:minutes:seconds when in example show it is houruminutesmsecondss without T, so you should do:
import datetime
my_time = '06-09-202014u59m04s'
date_object = datetime.datetime.strptime(my_time, '%d-%m-%Y%Hu%Mm%Ss')
print(date_object)
Output:
2020-09-06 14:59:04
You need to always make sure that your desired date format should match up with your required format.
from datetime import datetime
date_object = datetime.strptime("06-09-202015u59m04s", '%d-%m-%Y%Hu%Mm%Ss')
print(date_object.strftime('%Y/%m/%d %H:%M:%S'))
Output
2020/09/06 15:59:04
Apple is returning a strange format for the expiration date of a receipt:
2018-06-18 15:03:55 Etc/GMT
from datetime import datetime
dt = datetime.strptime('2018-06-18 15:03:55 Etc/GMT', '%Y-%m-%d %H:%M:%S %Z')
Etc and GMT are both the same.
I have tried to convert it like this into a datetime object, but failed doing so.
ValueError: time data '2018-06-18 15:03:55 Etc/GMT' does not match format '%Y-%m-%d %H:%M:%S %Z'
Why are there two time zones defined in the first place? And how can I make Python understanding it?
Actually, Etc/GMT appears to be a valid, existing time zone, just datetime does not seem to recognize it. You can do the following if you have the possibility to install pytz:
from datetime import datetime
import pytz
dt, tz = '2018-06-18 15:03:55 Etc/GMT'.rsplit(maxsplit=1) # rsplit() for simplicity, obviously re would make this safer
dto = datetime.strptime(dt, '%Y-%m-%d %H:%M:%S').replace(tzinfo=pytz.timezone(tz))
print(dto) # result: 2018-06-18 15:03:55+00:00
I am not sure if this is the correct approach..but if it helps.
import re
from dateutil.parser import parse
s = '2018-06-18 15:03:55 Etc/GMT'
print( parse(re.sub("(?<=:\d{2}\s).*\/", r"", s)) )
Output:
2018-06-18 15:03:55+00:00
I am using regex to remove Etc/ from the src datetime
Using dateutil to convert to datetime object.
This question already has answers here:
How to print a date in a regular format?
(25 answers)
Closed 6 years ago.
having trouble converting this string into a datetime this is what I tried so far in code:
import datetime
mystring = '2016/5/7/ 4:25:00 PM'
dateobj = datetime.datetime.strptime(mystring, "%Y-%B-%dT%H:%M:%S-%H:%M")
print (dateobj)
it throws me errors and I search in the library and still can't figure it out what I have wrong in my format.
Please any help I'll gratly apreciate it
You can do it as:
import datetime
mystring = '2016/5/7 4:25:00 PM'
dateobj = datetime.datetime.strptime(mystring, "%Y/%m/%d %I:%M:%S %p")
dateobj
Out[1]: datetime.datetime(2016, 5, 7, 16, 25)
dateobj1 = datetime.datetime.strptime(mystring, "%Y/%m/%d %I:%M:%S %p").strftime("%Y-%m-%d %I:%M:%S")
dateobj1
Out[2]: '2016-05-07 04:25:00'
The issue you are having is that in order to convert a date object you first have to create a date object. This means that your formatting will have to match the current string format '2016/5/7 4:25:00 PM' = "%Y/%m/%d %H:%M:%S %p". So we can now create a date obj and then format it using strftime with your new format "%Y-%B-%dT%H:%M:%S-%H:%M".
import datetime
mystring = '2016/5/7 4:25:00 PM'
dateobj = datetime.datetime.strptime(mystring, "%Y/%m/%d %H:%M:%S %p")
dateobj = datetime.datetime.strftime(dateobj, "%Y-%B-%dT%H:%M:%S-%H:%M")
print (dateobj)
the output recieved is a little funky, but it matches your format perfectly. Visit the datetime library to view the format codes and read up on strptime vs strftime. Good luck.
Output: 2016-May-07T04:25:00-04:25
I'm not sure where your format string came from, but it's wrong. It doesn't match your string format at all.
Take a look at the available options in the documentation.
You want this:
dateobj = datetime.datetime.strptime(mystring, "%Y/%m/%d/ %I:%M:%S %p")
This will get you a date object. You can then do this to reformat it how you want:
dateobj.strftime("%Y-%m-%d %I:%M:%S")
A couple things that were wrong with yours:
You used %H twice. This resulted in an error saying it'd be redefined.
%B is full month name (ie. January). You have a numeral.
The -s are incorrect since you have /s.
The T is not in your string at all.
Easily with dateutil.parser.parse
>>> from dateutil.parser import parse
>>> d = parse('2016/5/7/ 4:25:00 PM')
>>> d.strftime("%Y-%B-%dT%H:%M:%S-%H:%M")
'2016-May-07T16:25:00-16:25'
>>> d.strftime("%Y-%m-%d %I:%M:%S")
'2016-05-07 04:25:00'