Converting string (with timezone) to datetime in python - python

I aim to convert
stringtime = '2020-02-30 10:27:00+01:00'
so that I can compare it to
nowtime = datetime.datetime.utcnow()
using
if nowtime > stringtime:
print(1)
I tried strptime:
datetime.datetime.strptime(stringtime, '%Y-%m-%d %H:%M:%S')
But cannot find a format specification for the timezone in the strptime documentation.
I also tried
pandas.Timestamp(stringtime)
but I get ValueError: could not convert string to Timestamp.
How can this be done?

datetime.datetime.strptime(stringtime, '%Y-%m-%d %H:%M:%S%z')
Will give you the expected result %z is the format (Python3 only), however your original date is invalid as February doesnt have 30 days :)

First of all: Your stringtime is wrong, there exists no February 30th. ;)
You can achieve what you want with dateutil:
import dateutil.parser
stringtime = '2020-03-30 10:27:00+01:00'
dateutil.parser.isoparse(stringtime)
# datetime.datetime(2020, 3, 30, 10, 27, tzinfo=tzoffset(None, 3600))

Related

convert str date to datetime for timezone

I have an API that return this date string
strdate = '2019-10-07T06:09:28.984Z'
How do I convert it to a datetime object?
dt = datetime.datetime.strptime(strdate, '%Y-%m-%d')
If I use strptime like above i get "ValueError: unconverted data remains: T06:09:54.346Z"
What do I do if there is "T" and "Z" included in the string date? I want the data in local time. But is the string really timezone aware so I can convert it properly? In this case I know the timezone, but what if I did not know?
The error is because you're not including the time part in the format string. Do that:
datetime.strptime('2019-10-07T06:09:28.984Z', '%Y-%m-%dT%H:%M:%S.%f%z')
This results in:
datetime.datetime(2019, 10, 7, 6, 9, 28, 984000, tzinfo=datetime.timezone.utc)
If you want to convert this to a local timezone, do that:
from pytz import timezone
dt = datetime.strptime(strdate, '%Y-%m-%dT%H:%M:%S.%f%z')
local_dt = dt.astimezone(timezone('Asia/Tokyo'))
Demo: https://repl.it/repls/RotatingSqueakyCertifications
import datetime
strdate = '2019-10-07T06:09:28.984Z'
dt=datetime.datetime.strptime(strdate, "%Y-%m-%dT%H:%M:%S.%fZ")
print(dt)
# output - 2019-10-07 06:09:28.984000

Python strptime ValueError: time data does not match format

I have added timezones to my datetime column in my postgreSQL DB.
Now I have the error above everytime I want to compare dates.
On some points I have JSON requests, datetime objects are passed as strings, so I need to parse them, with the additonal timezone info I get:
ValueError: time data '2018-05-02 11:52:26.108540+02:00'
does not match format '%Y-%m-%d %H:%M:%S.%f+%Z'
Earlier I had:
2018-05-02 11:52:26.108540
which worked perfectly with:
%Y-%m-%d %H:%M:%S.%f
The new information which has been added is: +02:00
In the strptime docu it is telling me to use %z or %Z but it does not work.
EDIT:
I am using Python 3
The issue is the offset +02:00 you need to remove the colon ':' then it will work:
In[48]:
dt.datetime.strptime('2018-05-02 11:52:26.108540+0200', '%Y-%m-%d %H:%M:%S.%f%z')
Out[48]: datetime.datetime(2018, 5, 2, 11, 52, 26, 108540, tzinfo=datetime.timezone(datetime.timedelta(0, 7200)))
So you would need to go through all your datetime strings and remove this in order for strptime to parse it correctly
You need to remove the colon and use the small %z for this to work.
>>> s = '2018-05-02 11:52:26.108540+02:00'
>>> fmt = %Y-%m-%d %H:%M:%S.%f%z'
>>> time.strptime(s, fmt)
time.struct_time(tm_year=2018, tm_mon=5, tm_mday=2, tm_hour=11, tm_min=52, tm_sec=26, tm_wday=2, tm_yday=122, tm_isdst=-1)

Convert python timezone aware datetime string to utc time

I have a Python datetime string that is timezone aware and need to convert it to UTC timestamp.
'2016-07-15T10:00:00-06:00'
Most of the SO links talks about getting the current datetime in UTC but not on converting the given datetime to UTC.
Hi this was a bit tricky, but here is my, probably far from perfect, answer:
[IN]
import datetime
import pytz
date_str = '2016-07-15T10:00:00-06:00'
# Have to get rid of that bothersome final colon for %z to work
datetime_object = datetime.datetime.strptime(date_str[:-3] + date_str[-2:],
'%Y-%m-%dT%H:%M:%S%z')
datetime_object.astimezone(pytz.utc)
[OUT]
datetime.datetime(2016, 7, 15, 16, 0, tzinfo=<UTC>)

Converting dates in Python

I have dates in the form 26/11/2015. How can I convert them into the format 26-Nov-2015 and still keep them as dates and not strings?
Your question does not make much sense. If you keep them as dates, they have no format. The format is only manifested when you convert them to strings.
So the answer is: Store the dates as date (or datetime) objects, and use datetime.strftime with some specific format whenever you need them as a string:
>>> from datetime import date
>>> d = date(2016, 11, 26)
>>> d.strftime("%Y/%m/%d")
'2016/11/26'
>>> d.strftime("%d-%b-%Y")
'26-Nov-2016'
Conversely, use strptime to parse strings in different formats to dates:
>>> datetime.datetime.strptime("26-Nov-2015", "%d-%b-%Y")
datetime.datetime(2015, 11, 26, 0, 0)
from datetime import datetime
date = datetime.strptime('26/11/2015', '%d/%m/%Y')
print date.strftime("%d-%B-%Y")
In the above example, we are taking your input string 'dd/mm/yyyy' and turning it into a python datetime saving it to a variable called date (for future usage as per your request), and then printing it out in the format requested.
You want to use the datetime module I think. For example:
from datetime import date
a = date(2015, 11, 26)
a.strftime("%A %d of %B, %Y")
should give you 'Thursday 26 of November, 2015'
Or for your specific formatting request:
a.strftime("%d-%b-%Y") #'26-Nov-2015'
Hope this helps, good luck!

Python Time Delta time data does not match format error, can't find my mistake

time data '2015-07-30 20:32:01.521834' does not match format '%Y-%m-%d-%H:%M:%S.%f'
Can anyone tell me where I am going wrong?
You have a redundant dash - between the date and the time
Change:
'%Y-%m-%d-%H:%M:%S.%f'
to:
'%Y-%m-%d %H:%M:%S.%f'
>>>import datetime
>>>datetime.datetime.strptime('2015-07-30 20:32:01.521834', '%Y-%m-%d %H:%M:%S.%f')
>>>datetime.datetime(2015, 7, 30, 20, 32, 1, 521834)

Categories