I have two date strings (taken from user input and can vary greatly)
s1 = '2011:10:01:10:30:00'
s2 = '2011:10:01:11:15:00'
I wish to find the difference between the two as minutes.
How should I proceed to tackle this ?
import datetime
d1 = datetime.datetime.strptime('2011:10:01:10:30:00', '%Y:%m:%d:%H:%M:%S')
d2 = datetime.datetime.strptime('2011:10:01:11:15:00', '%Y:%m:%d:%H:%M:%S')
diff = (d2 - d1).total_seconds() / 60
If you need to handle arbitrary datetime formats, I don't believe the built in datetime library will do that for you. Perhaps check out something like:
http://www.egenix.com/products/python/mxBase/mxDateTime/
Using the datetime module, parse into a datetime object using strptime, then subtract. You'll get a timedelta. Then use timedelta.total_seconds() and divide by 60.
Use datetime to parse the string and convert into a base epoch time. Do the math. Convert back:
>>> from datetime import datetime
>>> s1 = '2011:10:01:10:30:00'
>>> s2 = '2011:10:01:11:15:00'
>>> d1=datetime.strptime(s1,'%Y:%m:%d:%I:%M:%S')
>>> d2=datetime.strptime(s2,'%Y:%m:%d:%I:%M:%S')
>>> d2-d1
datetime.timedelta(0, 2700)
>>> (d2-d1).total_seconds()/60
45.0
If you are looking for arbitrary date string parsing, check out DateUtil and the parse function.
The time module can be helpful for this.
import time
s1 = '2011:10:01:10:30:00'
s2 = '2011:10:01:11:15:00'
s1Time = time.strptime(s1, "%Y:%m:%d:%H:%M:%S")
s2Time = time.strptime(s2, "%Y:%m:%d:%H:%M:%S")
deltaInMinutes = (time.mktime(s2Time) - time.mktime(s1Time)) / 60.0
print deltaInMinutes, "minutes"
Related
I'm adding UTC time strings to Bitbucket API responses that currently only contain Amsterdam (!) time strings. For consistency with the UTC time strings returned elsewhere, the desired format is 2011-11-03 11:07:04 (followed by +00:00, but that's not germane).
What's the best way to create such a string (without a microsecond component) from a datetime instance with a microsecond component?
>>> import datetime
>>> print unicode(datetime.datetime.now())
2011-11-03 11:13:39.278026
I'll add the best option that's occurred to me as a possible answer, but there may well be a more elegant solution.
Edit: I should mention that I'm not actually printing the current time – I used datetime.now to provide a quick example. So the solution should not assume that any datetime instances it receives will include microsecond components.
If you want to format a datetime object in a specific format that is different from the standard format, it's best to explicitly specify that format:
>>> import datetime
>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
'2011-11-03 18:21:26'
See the documentation of datetime.strftime() for an explanation of the % directives.
Starting from Python 3.6, the isoformat() method is flexible enough to also produce this format:
datetime.datetime.now().isoformat(sep=" ", timespec="seconds")
>>> import datetime
>>> now = datetime.datetime.now()
>>> print unicode(now.replace(microsecond=0))
2011-11-03 11:19:07
In Python 3.6:
from datetime import datetime
datetime.now().isoformat(' ', 'seconds')
'2017-01-11 14:41:33'
https://docs.python.org/3.6/library/datetime.html#datetime.datetime.isoformat
This is the way I do it. ISO format:
import datetime
datetime.datetime.now().replace(microsecond=0).isoformat()
# Returns: '2017-01-23T14:58:07'
You can replace the 'T' if you don't want ISO format:
datetime.datetime.now().replace(microsecond=0).isoformat(' ')
# Returns: '2017-01-23 15:05:27'
Yet another option:
>>> import time
>>> time.strftime("%Y-%m-%d %H:%M:%S")
'2011-11-03 11:31:28'
By default this uses local time, if you need UTC you can use the following:
>>> time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
'2011-11-03 18:32:20'
Keep the first 19 characters that you wanted via slicing:
>>> str(datetime.datetime.now())[:19]
'2011-11-03 14:37:50'
I usually do:
import datetime
now = datetime.datetime.now()
now = now.replace(microsecond=0) # To print now without microsecond.
# To print now:
print(now)
output:
2019-01-13 14:40:28
Since not all datetime.datetime instances have a microsecond component (i.e. when it is zero), you can partition the string on a "." and take only the first item, which will always work:
unicode(datetime.datetime.now()).partition('.')[0]
As of Python 3.6+, the best way of doing this is by the new timespec argument for isoformat.
isoformat(timespec='seconds', sep=' ')
Usage:
>>> datetime.now().isoformat(timespec='seconds')
'2020-10-16T18:38:21'
>>> datetime.now().isoformat(timespec='seconds', sep=' ')
'2020-10-16 18:38:35'
We can try something like below
import datetime
date_generated = datetime.datetime.now()
date_generated.replace(microsecond=0).isoformat(' ').partition('+')[0]
>>> from datetime import datetime
>>> dt = datetime.now().strftime("%Y-%m-%d %X")
>>> print(dt)
'2021-02-05 04:10:24'
f-string formatting
>>> import datetime
>>> print(f'{datetime.datetime.now():%Y-%m-%d %H:%M:%S}')
2021-12-01 22:10:07
This I use because I can understand and hence remember it better (and date time format also can be customized based on your choice) :-
import datetime
moment = datetime.datetime.now()
print("{}/{}/{} {}:{}:{}".format(moment.day, moment.month, moment.year,
moment.hour, moment.minute, moment.second))
I found this to be the simplest way.
>>> t = datetime.datetime.now()
>>> t
datetime.datetime(2018, 11, 30, 17, 21, 26, 606191)
>>> t = str(t).split('.')
>>> t
['2018-11-30 17:21:26', '606191']
>>> t = t[0]
>>> t
'2018-11-30 17:21:26'
>>>
You can also use the following method
import datetime as _dt
ts = _dt.datetime.now().timestamp()
print("TimeStamp without microseconds: ", int(ts)) #TimeStamp without microseconds: 1629275829
dt = _dt.datetime.now()
print("Date & Time without microseconds: ", str(dt)[0:-7]) #Date & Time without microseconds: 2021-08-18 13:07:09
Current TimeStamp without microsecond component:
timestamp = list(str(datetime.timestamp(datetime.now())).split('.'))[0]
I have data of timedeltas which looks like this:
time_delta = '+414 00:45:41.004000'
So, these values are strings and they are of the format ddd hh:mm:ss.f. I now want to get this deltas to seconds. I tried to use .total_seconds() but it did not work.
How could I achieve what I am trying to do?
If you always assume the same input format, you can build a function as below (result to be checked with a simple case) :
import datetime as dt
def parseTimeDelta(time_delta_str):
splitted = time_delta_str.split(' ')
day_part = int(splitted[0][1:])
time_part = dt.datetime.strptime(splitted[1], "%H:%M:%S.%f")
delta = dt.timedelta(days=day_part, hours=time_part.hour, minutes=time_part.minute, seconds=time_part.second,microseconds=time_part.microsecond)
return delta.total_seconds()
time_delta = '+414 00:45:41.004000'
parseTimeDelta(time_delta)
can do this with pandas library
import pandas as pd
# Create the Timedelta object
td = pd.Timedelta('3 days 06:05:01.000000111')
print(td)
print(td.seconds)
Unfortunately we can't create a timedelta with a formatted string directly, but we can get a similar effect with regex then unpack parsed values into a timedelta.
import re
import datetime
# Create parser for your time format with named groups that match timedelta kwargs
time_parser = re.compile(r"\+(?P<days>\d+)\s+(?P<hours>\d{2}):(?P<minutes>\d{2}):(?P<seconds>\d{2})\.(?P<microseconds>\d+)")
# Get the values from your example string
regex_match = time_parser.match("+414 00:45:41.004000")
time_dict = regex_match.groupdict()
# Convert the time values to integers from strings
timedelta_kwargs = {k: int(v) for k, v in time_dict.items()}
# Make a time delta object
delta = datetime.timedelta(**timedelta_kwargs)
# Get total seconds
delta_in_seconds = delta.total_seconds()
Organise that into some functions and you'll get the functionality you're looking for with standard python packages.
I have time values in text as:
a="060453"
b="135309"
I want to convert the above into "HH:MM:SS" format and also get the difference in the same format.
13:53:09 - 06:04:53 = 07:49:06
Regards
I don't think your math is right but I think this is kind of what you want:
>>> import datetime
>>> print datetime.datetime.strptime("135309", "%H%M%S") - datetime.datetime.strptime("060453", "%H%M%S")
7:48:16
>>>
This should get you the timedelta you need-
from datetime import datetime
a="060453"
b="135309"
a = datetime.strptime(a,'%H%M%S')
b = datetime.strptime(b,'%H%M%S')
print(b-a)
So the I generally understand how I would convert from mm/dd/yyyy format to yyyy-mm-dd if the initial date given was something like 01/04/2014. However I am only given 1/4/2014 (without zeroes). Is there a clean and more efficient way of converting this in python 3 rather than writing a bunch of if statements?
>>> from datetime import datetime
>>> date = datetime.strptime("1/4/2014", "%m/%d/%Y")
>>> datetime.strftime(date, "%Y-%m-%d")
'2014-01-04'
Python datetime strftime()
How strptime and strftime work
from datetime import datetime
date = datetime.strptime("1/4/2014", "%m/%d/%Y")
print(datetime.strftime(date, "%Y-%m-%d"))
'2014-01-04'
Abdou's suggestion using the datetime module is best, because you get the benefit of datetime's sanity-checking of the values. If you want to do it using only string manipulations, then notice that you can supply a fill character when invoking a string's rjust method:
>>> "1".rjust(2,"0")
'01'
so:
>>> x = "1/4/2345"
>>> f = x.split("/")
>>> f[2] + "-" + f[0].rjust(2,"0") + "-" + f[1].rjust(2,"0")
'2345-01-04'
Assuming that you don't need to validate the input dates, you don't need any if statements, or date processing functions: you can do it all with the string .split and .format methods.
def us_date_to_iso(us_date):
return '{2}-{0:>02}-{1:>02}'.format(*us_date.split('/'))
# test
for s in ('1/4/2014', '1/11/1999', '31/5/2015', '25/12/2016'):
print(s, us_date_to_iso(s))
output
1/4/2014 2014-01-04
1/11/1999 1999-01-11
31/5/2015 2015-31-05
25/12/2016 2016-25-12
This is my code - I want to convert a string into a time in Python - it sort of works:
import datetime
firstTime = ("18:08:14")
firstTime = datetime.datetime.strptime(firstTime, "%H:%M:%S")
print (firstTime)
The problem is, I get '1900-01-01 18:08:14' instead of just '18:08:14'. I know this is a fairly basic thing, but I'm new to Python and any help would be appreciated.
As my comment suggests, use a time class rather than datetime since you don't need the date part:
>>> from datetime import datetime
>>> firsttime = datetime.strptime('18:08:14','%H:%M:%S')
>>> print(firsttime)
1900-01-01 18:08:14
>>> print(firsttime.time())
18:08:14
or simply:
>>> firsttime = datetime.strptime('18:08:14','%H:%M:%S').time()
>>> print(firsttime)
18:08:14
try this..
>>> from datetime import datetime
>>> date=datetime.now()
>>> date.strftime('%H:%M:%S')
'23:55:17'
>>>
Your code seems fine. Just change strptime to strftime.
import datetime
firstTime = ("18:08:14")
firstTime = datetime.datetime.strftime(firstTime, "%H:%M:%S")
print (firstTime)
strptime takes a string and convert to datetime object.
strftime creates formatted string from given date,time,datetime object according to a specific format