Convert text to Time format in python - python

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)

Related

Converting timezone to new format and inserting into list in python [duplicate]

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]

Python: convert date format YYYY-mm-dd to dd-MON-yyyy with abbreviated month

I have a date that is a string in this format:
'2021-01-16'
And need to convert it to a string in this format:
'16-JAN-2021'
I am able to get most of it like this:
x = datetime.strptime('2021-01-16', '%Y-%m-%d')
x.strftime('%d-%b-%Y')
But the month is not fully capitalized:
'16-Jan-2021'
Just use upper() to capitalize the output string:
from datetime import datetime
x = datetime.strptime('2021-01-16', '%Y-%m-%d')
print(x.strftime('%d-%b-%Y').upper())
# 16-JAN-2021
You were almost there. Simply use upper().
>>> from datetime import datetime
>>> datetime.strptime('2021-01-16', '%Y-%m-%d').strftime('%d-%b-%Y').upper()
'16-JAN-2021'
x.strftime('%d-%b-%Y').upper()
I read answers with upper() function, here is another way using %^b
from datetime import datetime
date = datetime.strptime('2011-01-16', '%Y-%m-%d')
formatted_date = date.strftime('%d-%^b-%Y')
print(formatted_date)
Goodluck!

Converting to_datetime but keeping original time

I am trying to convert string to Datetime- but the conversion adds 5 hours to the original time. How do I convert but keep the time as is?
>>> import pandas as pd
>>> t = pd.to_datetime("2016-09-21 08:56:29-05:00", format='%Y-%m-%d %H:%M:%S')
>>> t
Timestamp('2016-09-21 13:56:29')
The conversion doesn't add 5 hours to the original time. Pandas just detects that your datetime is timezone-aware and converts it to naive UTC. But it's still the same datetime.
If you want a localized Timestamp instance, use Timestamp.tz_localize() to make t a timezone-aware UTC timestamp, and then use the Timestamp.tz_convert() method to convert to UTC-0500:
>>> import pandas as pd
>>> import pytz
>>> t = pd.to_datetime("2016-09-21 08:56:29-05:00", format='%Y-%m-%d %H:%M:%S')
>>> t
Timestamp('2016-09-21 13:56:29')
>>> t.tz_localize(pytz.utc).tz_convert(pytz.timezone('America/Chicago'))
Timestamp('2016-09-21 08:56:29-0500', tz='America/Chicago')
To achieve what you want you can remove the "-5:00" from the end of your time string "2016-09-21 08:56:29-05:00"
However, Erik Cederstrand is correct in explaining that pandas is not modifying the time, it's simply displaying it in a different format.

String to time conversion issue in python

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

python: difference of two timedate strings

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"

Categories

Resources