How to convert date string from database to something comparable? - python

I have timestamps in database formatted like this: 2022-05-03 10:20:30.687 +0200.
I'm trying to convert that to a format that would allow me to compare two timestamps.
But, when I try to print that with
print(datetime.fromtimestamp(last_timestamp, pytz.utc))
I get the following error:
E TypeError: 'datetime.datetime' object cannot be interpreted as an integer
How can I get this to work?
Edit:
It appears I was overthinking this: comparing the strings directly works as expected.

time_stamp1=str('2022-05-03 10:20:30.687 +0200')
time_stamp2=str('2022-05-04 11:21:35.687 +0200')
t1 = datetime.strptime(time_stamp1, "%Y-%m-%d %H:%M:%S.%f %z")
t2 = datetime.strptime(time_stamp2, "%Y-%m-%d %H:%M:%S.%f %z")
diff = t1 - t2
check datetime python for more

As you can read from the documentation, the datetime.fromtimestamp function converts a date in posix format (a 32bit integer) to a local date format.
Return the local date and time corresponding to the POSIX timestamp,
such as is returned by time.time(). If optional argument tz is None or
not specified, the timestamp is converted to the platform’s local date
and time, and the returned datetime object is naive.
If your date is in string format, use the function datetime.strptime(date_time_str, format)

Related

Convert custom string date to date

Is there a way to convert a string date that is stored in some non-traditional custom manner into a date using datetime (or something equivalent)? The dates I am dealing with are S3 partitions that look like this:
year=2023/month=2/dayofmonth=3
I can accomplish this with several replaces but im hoping to find a clean single operation to do this.
You might provide datetime.datetime.strptime with format string holding text, in this case
import datetime
dt = datetime.datetime.strptime("year=2023/month=2/dayofmonth=3","year=%Y/month=%m/dayofmonth=%d")
d = dt.date()
print(d) # 2023-02-03
you can do that converting your string into a date object using "datetime" combined with strptime() method.
The strtime() takes two arguments, the first is the string to be parsed, and the second a string with the format.
Here's an example:
from datetime import datetime
# your string
date_string = "year=2023/month=2/dayofmonth=3"
# parse the string into a datetime object
date = datetime.strptime(date_string, "year=%Y/month=%m/dayofmonth=%d")
# print the datetime object
print(date)

Converting a datetime to local time based on timezone in Python3

I have a question related to dates and time in Python.
Problem:
date = datetime.datetime.strptime(str(row[1]), "%Y-%m-%d %H:%M:%S")
localtime = date.astimezone(pytz.timezone("Europe/Brussels"))
formattedDate = localtime.strftime("%Y-%m%-%d")
In the code above, str(row[1]) gives back a UTC datetime coming from a mysql database: 2022-02-28 23:00:00
I parse this as a datetime and change the timezone to Europe/Brussels.
I then format it back to a string.
Expected result:
I'd like to return the date in local time. Europe/Brussels adds one hour so I would expect that strftime returns 2022-03-01, but it keeps returning 2022-02-28.
Can somebody help?
date is a naïve date, without timezone, because no timezone information was in the string you parsed. Using astimezone on that simply attaches timezone information to it, turning a naïve date into an aware one. It obviously can't convert any times, because it doesn't know what to convert from.
This also already contains the answer: make the date aware that it's in UTC first before trying to convert it to a different timezone:
date = datetime.datetime.strptime(...).astimezone(datetime.timezone.utc)
Ah, I see!
I ended up doing this, basically the same as you mentioned:
from_zone = tz.gettz('UTC')
to_zone = tz.gettz('Europe/Brussels')
utcdate = datetime.datetime.strptime(str(row[1]), "%Y-%m-%d %H:%M:%S")
utcdate = utcdate.replace(tzinfo=from_zone)
localdate = utcdate.astimezone(to_zone)
formattedLocalDate = localdate.strftime("%Y%m%d");
The naïve date gets UTC aware by the utcdate.replace(tzinfo=from_zone).
Thanks for helping!

Datetime still showing time component

I have this line of code-
future_end_date = datetime.strptime('2020/02/29','%Y/%m/%d')
and when I print this-
2020-02-29 00:00:00
it still shows the time component even though I did strptime
This is because strptime returns datetime rather than date. Try converting it to date:
datetime.strptime('2020/02/29','%Y/%m/%d').date()
datetime.strptime(date_string, format) function returns a datetime
object corresponding to date_string, parsed according to format.
When you print datetime object, it is formatted as a string in ISO
8601 format, YYYY-MM-DDTHH:MM:SS
So you need to convert the datetime into date if you only want Year, month and Day -
datetime.strptime('2020/02/29','%Y/%m/%d').date()
Another possible way is using strftime() method which returns a string representing date and time using date, time or datetime object.
datetime.strptime('2020/02/29','%Y/%m/%d').strftime('%Y/%m/%d')
Output of both code snippets -
2020/02/29

replace hours in a datetime type python

I have a datetime type mydate in %Y-%m-%dT%H:%M:%S format.
I want to replace the hours
I did this using mydate.replace() method
Now I want to comapre it with another specific date -> myNEWdate whose format is %Y-%m-%d %H:%M:%S :
newdate = mydate.replace(hour = islot)
print newdate
appointmentDict[mydate]['time_start'] = datetime.strptime(str(newdate),"%Y/%m/%d %H:%M:%S")
The date is printed as 2015-06-26 08:00:00
and I get the error
ValueError: time data '2015-06-26 08:00:00' does not match format '%Y/%m/%d %H:%M:%S'
What should I do to resolve this
You need to set the correct format
datetime.strptime(str(newdate),"%Y-%m-%d %H:%M:%S")
To solve the exception. Although converting from datetime 2 string and backwards doesn't make much sense, as mentioned in the comments.

Date as Type: type and determining time left

An API I am working with returns and end_date attribute of type: type. It's formatted like this: u'2013-04-15 14:00:00'. I simply want to subtract today -- datetime.date(2013, 4, 9) -- from whatever the end_date is to determine the time remaining. I have looked through the documentation for the python Datetime module, but I haven't been able to figure out how to take the end_date attribute and convert it into something I can use to subtract today from. Am I missing something in the library? What's the best way to do this?
date_a = datetime.strptime('2013-04-15 14:00:00','%Y-%m-%d %H:%M:%S')
date_b = datetime.strptime('2013-04-15 14:02:05','%Y-%m-%d %H:%M:%S')
elapsed_time = date_b - date_a
then: print elapsed_time.total_seconds() will return 125 seconds. my elapsed_time is of timedelta type. For example elapsed_time.days could also give you the number of days.
%Y-%m-%d %H:%M:%S is the format given for the date parser. Check Python doc for strptime format in the paragraph 8.1.7. strftime() and strptime() Behavior.

Categories