String to time conversion issue in python - 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

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!

Convert text to Time format in 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)

Convert date to ordinal python?

I want to convert
2010-03-01 to 733832
I just found this toordinal code
d=datetime.date(year=2010, month=3, day=1)
d.toordinal()
from this
But i want something more like
d=datetime.date('2010-03-01')
d.toordinal()
Thanks in advance
You'll need to use strptime on the date string, specifying the format, then you can call the toordinal method of the date object:
>>> from datetime import datetime as dt
>>> d = dt.strptime('2010-03-01', '%Y-%m-%d').date()
>>> d
datetime.date(2010, 3, 1)
>>> d.toordinal()
733832
The call to the date method in this case is redundant, and is only kept for making the object consistent as a date object instead of a datetime object.
If you're looking to handle more date string formats, Python's strftime directives is one good reference you want to check out.
like this:
datetime.strptime("2016-01-01", "%Y-%m-%d").toordinal()
You need to firstly convert the time string to datetime object using strptime(). Then call .toordinal() on the datetime object
>>> from datetime import datetime
>>> date = datetime.strptime('2010-03-01', '%Y-%M-%d')
>>> date.toordinal()
733773
It is even better to create a function to achieve this as:
def convert_date_to_ordinal(date):
return datetime.strptime(date, '%Y-%M-%d').toordinal()
convert_date_to_ordinal('2010-03-01')
#returns: 733773

Print datetime in ISO format without milliseconds

I'm trying to serialize datetime in an API, but I don't want milliseconds. What I want is here: https://en.wikipedia.org/wiki/ISO_8601 - "2015-09-14T17:51:31+00:00"
tz = pytz.timezone('Asia/Taipei')
dt = datetime.datetime.now()
loc_dt = tz.localize(dt)
Try A:
loc_dt.isoformat()
>> '2015-09-17T10:46:15.767000+08:00'
Try B:
loc_dt.strftime("%Y-%m-%dT%H:%M:%S%z")
>> '2015-09-17T10:46:15+0800'
The latter one is almost perfect except it's missing the colon in the timezone part. How can I solve this without string manipulation (deleting milliseconds or adding colon)?
You can replace the microseconds with 0 and use isoformat:
import pytz
from datetime import datetime
tz = pytz.timezone('Asia/Taipei')
dt = datetime.now()
loc_dt = tz.localize(dt).replace(microsecond=0)
print loc_dt.isoformat()
2015-09-17T19:12:33+08:00
If you want to keep loc_dt as is do the replacing when you output:
loc_dt = tz.localize(dt)
print loc_dt.replace(microsecond=0).isoformat()
As commented you would be better passing the tz to datetime.now:
dt = datetime.now(tz)
The reasons are discussed in pep-0495, you might also want to add an assert to catch any bugs when doing the replace:
ssert loc_dt.resolution >= timedelta(microsecond=0)
Since python 3.6, datetime.isoformat accepts a timespec keyword to pick a precision. This argument gives the smallest time unit you want to be included in the output:
>>> loc_dt.isoformat()
'2022-10-21T19:59:59.991999+08:00'
>>> loc_dt.isoformat(timespec='seconds')
'2022-10-21T19:59:59+08:00'
>>> loc_dt.isoformat(timespec='milliseconds')
'2022-10-21T19:59:59.991+08:00'
Notice how the time is truncated and not rounded.
You can also use timespec to remove seconds/minutes:
>>> loc_dt.isoformat(timespec='minutes')
'2022-10-21T19:59+08:00'
>>> loc_dt.isoformat(timespec='hours')
'2022-10-21T19+08:00'
This all assume you ran the following setup script beforehand:
from datetime import datetime
import pytz
tz = pytz.timezone('Asia/Taipei')
dt = datetime.now()
loc_dt = tz.localize(dt)
Also note that this works without timezone:
>>> from datetime import datetime
>>> now = datetime.now()
>>> now.isoformat(timespec='minutes')
>>> '2022-10-21T19:59'

Categories

Resources