Subtracting datetime in string format with datetime format - python

I have 2 variables.
One is datetime in string format and the other is datetime in datetime.datetime format.
For example -
2021-09-06T07:58:19.032Z # string
2021-09-05 14:58:10.209675 # datetime.datetime
I want to find out the difference between these 2 times in seconds.
I think we need to have both in datetime before we can do this subtraction.
I'm having a hard time converting the string to datetime.
Can someone please help.

You can convert the string into datetime object with strptime()
An example with your given dates:
from datetime import datetime
# Assuming this is already a datetime object in your code, you don't need this part
# I needed this part to be able to use it as a datetime object
date1 = datetime.strptime("2021-09-05 14:58:10.209675", "%Y-%m-%d %H:%M:%S.%f")
## The part where the string is converted to datetime object
# Since the string has "T" and "Z", we will have to remove them before we convert
formatted = "2021-09-06T07:58:19.032Z".replace("T", " ").replace("Z", "")
>>> 2021-09-06 07:58:19.032
# Finally, converting the string
date2 = datetime.strptime(formatted, "%Y-%m-%d %H:%M:%S.%f")
# Now date2 variable is a datetime object
# Performing a simple operation
print(date1 - date2)
>>> -1 day, 6:59:51.177675

Convert the str to datetime via strptime() and then get the difference of the 2 datetime objects in seconds via total_seconds().
from datetime import datetime, timezone
# Input
dt1_str = "2021-09-06T07:58:19.032Z" # String type
dt2 = datetime(year=2021, month=9, day=5, hour=14, minute=58, second=10, microsecond=209675, tzinfo=timezone.utc) # datetime type
# Convert the string to datetime
dt1 = datetime.strptime(dt1_str, "%Y-%m-%dT%H:%M:%S.%f%z")
# Subtract the datetime objects and get the seconds
diff_seconds = (dt1 - dt2).total_seconds()
print(diff_seconds)
Output
61208.822325

The first string time you mention could be rfc3339 format.
A module called python-dateutil could help
import dateutil.parser
dateutil.parser.parse('2021-09-06T07:58:19.032Z')
datetime module could parse this time format by
datetime.datetime.strptime("2021-09-06T07:58:19.032Z","%Y-%m-%dT%H:%M:%S.%fZ")
But this way may cause trouble when get a time in another timezone because it doesn't support timezone offset.

Related

How to convert the local time into utc time in python

I am trying to convert the local time into UTC time. But getting the below error.
Error: an integer is required (got type str)
from datetime import datetime
starts_date = '2021-07-30 09:30:00'(timestamp without time zone)
ts = starts_date
x = datetime.utcfromtimestamp(ts)
x_ts = x.timestamp()
Be sure that datetime is imported correctly as from datetime import datetime. Can be a bit confusing but the method utcfromtimestamp belongs to datetime.datetime and not datetime itself.
Here is a working example to convert a timestamp of (now) to a UTC timestamp.
from datetime import datetime as dt
# Create a timestamp object for now.
ts = dt.timestamp(dt.now())
# Convert now to a UTC timestamp.
dt.utcfromtimestamp(ts).timestamp()
>>> 1627637013.657752
datetime.utcfromtimestamp() takes an integer that represent the amount of seconds passed since January 1st 1970.
This means with
from datetime import datetime as dt
print(dt.utcfromtimestamp(0))
you get
1970-01-01 00:00:00

How to combine dates and times?

I want to add a time to a datetime. My initial datetime is: initial_datetime='2015-11-03 08:05:22' and is a string and this_hour and this_min are strings too. I use:
time='-7:00'
time = time.split(':')
this_hour = time[0]
this_min = time[1]
initial_datetime='2015-11-03 08:05:22'
new_date = datetime.combine(initial_datetime, time(this_hour, this_min))
+ timedelta(hours=4)
But there comes an error:
'str' object is not callable.
My desired output is the initial_datetime plus my time (in this case -7 hours ) and then add 4 hours. So, in my example, the new date should be '2015-11-03 05:05:22'.
datetime.combine is typically used to combine a date object with a time object rather than incrementing or decrementing a datetime object. In your case, you need to convert your datetime string to a datetime object and convert the parts of your time string to integers so you can add them to your datetime with timedelta. As an aside, be careful about using variable names, like time, that conflict with your imports.
from datetime import datetime, timedelta
dtstr = '2015-11-03 08:05:22'
tstr = '-7:00'
hours, minutes = [int(t) for t in tstr.split(':')]
dt = datetime.strptime(dtstr, '%Y-%m-%d %H:%M:%S') + timedelta(hours=hours+4, minutes=minutes)
print(dt)
# 2015-11-03 05:05:22

Is there a way to extract time from datetime objects in Python?

I want to extract time values from a datetime object in Python. This is the code I used:
t = '2018-12-16 17:59:00'
t.strftime('%H:%M:%S')
There is clearly something wrong with the code because I am getting this error:
AttributeError: 'str' object has no attribute 'strftime'
I am using Python 3 and I need to convert around 30000 datetime values.
from datetime import datetime as dt
t = '2018-12-16 17:59:00'
t = dt.strptime(t, '%Y-%m-%d %H:%M:%S')
print(t.strftime('%H:%M:%S'))
in datetime methods
strptime is the mehtod to convert from string to datetime
strftime is the method to convert from datetime to string
That's a string, not a datetime object. You should probably be using a datetime object:
t = datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])
But if you want to use your string, you can splice it into two (space-separated) parts:
t = t.split() # t = ['2018-12-16', '17:59:00']
Then take the first part:
date = t[0]

'datetime.datetime' object has no attribute 'read'

Users in my app have date_joined fields that are in this format: 2014-12-14 14:46:43.379518+00:00
In order to pass this datetime along to Intercom.io, it must be a UNIX timestamp like this: 1426020706 (this is not the same time, just an example).
I've tried several methods I've read here on Stack Overflow (nothing in this question has the same starting time format: Converting datetime.date to UTC timestamp in Python), but none have worked. mktime() seemed promising, but I got "'datetime.datetime' object has no attribute 'mktime'."
I just tried this:
import time
import dateutil.parser
import member.models import Member
member = Member.objects.get(email="aspeksnijder#outlook.com")
date_joined = member.date_joined
dt = dateutil.parser.parse(date_joined)
print int(time.mktime(dt.timetuple()))
It returned "'datetime.datetime' object has no attribute 'read'". How can I accomplish this?
It seems you have an aware datetime object. If you print it then it looks like:
2014-12-14 14:46:43.379518+00:00
To be sure print(repr(date_joined)).
Converting datetime.date to UTC timestamp in Python shows several ways how you could get the timestamp e.g.,
timestamp = date_joined.timestamp() # in Python 3.3+
Or on older Python versions:
from datetime import datetime
# local time = utc time + utc offset
utc_naive = date_joined.replace(tzinfo=None) - date_joined.utcoffset()
timestamp = (utc_naive - datetime(1970, 1, 1)).total_seconds()
Note: timestamp = calendar.timegm(date_joined.utctimetuple()) would also work in your case but it may return a wrong result silently if you pass it a naive datetime object that represents local time by mistake.
If your input is a time string then convert the time string into a datetime object first.
What about (using the dateutil and pytz packages):
import dateutil.parser
from datetime import datetime
import calendar
import pytz
def str2ts(s):
''' Turns a string into a non-naive datetime object, then get the timestamp '''
# However you get from your string to datetime.datetime object
dt = dateutil.parser.parse(s) # String to non-naive datetime
dt = pytz.utc.normalize(dt) # Normalize datetime to UTC
ts = calendar.timegm(dt.timetuple()) # Convert UTC datetime to UTC timestamp
return int(ts)
def ts2str(ts):
'''Convert a UTC timestamp into a UTC datetime, then format it to a string'''
dt = datetime.utcfromtimestamp(ts) # Convert a UTC timestamp to a naive datetime object
dt = dt.replace(tzinfo=pytz.utc) # Convert naive datetime to non-naive
return dt.strftime('%Y-%m-%d %H:%M:%S.%f%z')
Which we can test with:
# A list of strings corresponding to the same time, with different timezone offsets
ss = [
'2014-12-14 14:46:43.379518+00:00',
'2014-12-14 15:46:43.379518+01:00',
'2014-12-14 16:46:43.379518+02:00',
'2014-12-14 17:46:43.379518+03:00',
]
for s in ss:
ts = str2ts(s)
s2 = ts2str(ts)
print ts, s2
Output:
1418568403 2014-12-14 14:46:43.000000+0000
1418568403 2014-12-14 14:46:43.000000+0000
1418568403 2014-12-14 14:46:43.000000+0000
1418568403 2014-12-14 14:46:43.000000+0000
These output all the same timestamps, and "verification" formatted strings.
You can try the following Python 3 code:
import time, datetime
print(time.mktime(datetime.datetime.strptime("2014-12-14 14:46:43.379518", '%Y-%m-%d %H:%M:%S.%f').replace(tzinfo=datetime.timezone.utc).timetuple()))
which prints:
1418568403.0
I had that problem when I used input from Django's DateField, which is displayed in a form of XXXX-YY-ZZ: parse(django_datefield) causes the exception.
The solution: use str(django_datefield).
parse(str(django_datefield))
I know this is an old post, but I want to highlight that the answer is likely what #Peter said in his comment:
It looks like member.date_joined is already a datetime object, and there's no need to parse it. – Peter Feb 25 '17 at 0:33
So-- your model probably already parses into a datetime.datetime object for you.

python: convert date timestamp to epoch unix time and figure out number of days remaining?

I want to convert 2014-08-14 20:01:28.242 into a unix timestamp 245293529385 and subtract this by the current timestamp in order to figure out how many days have past and are ultimately remaining by subtracting this value from 14.
Scenario: user signs up and I want to count down the number of days remaining in their trial.
time.strptime to the rescue! Use the format string %Y-%m-%d %H:%M:%S.%f. For example:
import time
t = '2014-08-14 20:01:28.242'
ts = time.strptime(t, '%Y-%m-%d %H:%M:%S.%f')
timestamp = time.mktime(ts)
Now to convert it to a datetime (from: How do you convert a Python time.struct_time object into a datetime object? ):
from datetime import datetime
dt = datetime.fromtimestamp(timestamp)
There are two parts:
Convert input time string into datetime object
#!/usr/bin/env python
from datetime import datetime
dt = datetime.strptime('2014-08-14 20:01:28.242', '%Y-%m-%d %H:%M:%S.%f')
Convert datetime object to Unix time ("seconds since epoch")
The result depends on what time zone is used for the input time e.g., if the input is in UTC then the corresponding POSIX timestamp is:
timestamp = (dt - datetime(1970,1,1)).total_seconds()
# -> 1408046488.242
If your input is in the local timezone then see How do I convert local time to UTC in Python?

Categories

Resources