Removing milliseconds from datetime object in Python - python

I am trying to remove the milliseconds(28109) from this string 2017-09-12 22:33:55.28109 in Python.
code:
import datetime as dt
from datetime import date,datetime
created_date = datetime.fromtimestamp(ctime)
d=datetime.strptime(created_date, "%Y-%m-%d %H:%M:%S.%fZ")
created_date = datetime.strftime(d, "%m/%d/%Y %I:%M:%S %p")
print(created_date)
Error:
`d=datetime.strptime(created_date, "%Y-%m-%d %H:%M:%S.%fZ")`
TypeError: must be str, not datetime.datetime

You already have a datetime object, you do not need to parse it again. The datetime.fromtimestamp() call was enough.
Remove the datetime.strptime() line.
created_date = datetime.fromtimestamp(ctime)
created_date = created_date.strftime("%m/%d/%Y %I:%M:%S %p")
print(created_date)
I also changed your strftime() call, it is a method, you just call it on the datetime object you have.
I suspect that you printed the return value of the datetime.fromtimestamp() call, and got confused. The str() conversion of a datetime() instance formats the value as a ISO 8601 string. Note that even if you did have a string, you used the wrong format (there is no timezone in that string, so %Z does not apply).
If you needed a datetime object, rather than a formatted string, you could also just have converted your timestamp to an integer; the microseconds are captured in the decimal portion of the timestamp:
>>> ctime = 1505252035.28109
>>> datetime.fromtimestamp(ctime)
datetime.datetime(2017, 9, 12, 22, 33, 55, 281090)
>>> datetime.fromtimestamp(int(ctime))
datetime.datetime(2017, 9, 12, 22, 33, 55)
>>> print(_)
2017-09-12 22:33:55

You can use time as well to achieve what you want.
import time
ctime = "2017-09-12 22:33:55.28109"
x = time.strptime(ctime.split('.')[0],'%Y-%m-%d %H:%M:%S')
x = time.strftime('%m/%d/%Y %I:%M:%S %p', x)
print (x)
'09/12/2017 10:33:55 PM'

Related

Correct Python datetime FMT

what is wrong with my FMT formatting for datetime? My date is formatted as follows:
mytime = '2021-12-06T13:52:41.864+0000'
I am trying to parse it with
FMT = '%Y-%m-%dT%H:%M:%S.%f+%Z'
and
FMT = '%Y-%m-%dT%H:%M:%S.%f+0000'
To be able to do:
datetime.strptime(mytime, FMT)
Both my solutions do not work. Any idea?
remove + and use z instead of Z.
from datetime import datetime
mytime = '2021-12-06T13:52:41.864+0000'
datetime.strptime(mytime, '%Y-%m-%dT%H:%M:%S.%f%z')
output:
datetime.datetime(2021, 12, 6, 13, 52, 41, 864000, tzinfo=datetime.timezone.utc)
You're using the wrong timezone directive in your FMT, use %z, not +%Z.
%z: UTC offset in the form +HHMM or -HHMM.

Convert string in format datetime

I have this date that comes to me in the following format and it is string type
from datetime import datetime
fecha_str = "2021-09-27T20:42:34.099000Z"
fecha_datetime = datetime.strptime(fecha_str,'%d del %m de %Y a las %H:%M')
I need to transform it into a datetime type varibale so that I can manipulate it and only show the information that is needed.
The format string you're passing to strptime() is for an output (ie, used with strftime()). The timestamp you are parsing is in UTC (the trailing 'Z'), and ISO8601 format with milliseconds.
>>> fecha_str = "2021-09-27T20:42:34.099000Z"
>>> fecha_datetime = datetime.strptime(fecha_str, "%Y-%m-%dT%H:%M:%S.%fZ")
>>> fecha_datetime
datetime.datetime(2021, 9, 27, 20, 42, 34, 99000)
from datetime import datetime
date_time_str = '18/09/19 01:55:19'
date_time_obj = datetime.strptime(date_time_str, '%d/%m/%y %H:%M:%S')
print ("The type of the date is now", type(date_time_obj))
print ("The date is", date_time_obj)

Parse and extract values from time format in python

I am trying to parse and extract values from my time data 2018-03-11 13:15:31.734874+01:00.
I'm using strptime() to do this with the %Y %m %d %H:%M:%S.%f %Z format but I am getting this error:
ValueError: time data '2018-03-11 13:15:31.734874+01:00' does not match format '%Y %m %d %H:%M:%S.%f %Z'
Also, I don't know how to handle the +1:00 in my time data. Can anyone help?
There are two problems here to solve.
First is the format string. It should be %Y-%m-%d %H:%M:%S.%f%z to match exact date separators and timezone sequence (without space).
From strftime and strptime Behavior:
%z (lower case) UTC offset in the form +HHMM or -HHMM (empty string if the object is naive). (empty), +0000, -0400, +1030
Second is the colon (:) in timezone offset '+01:00'. That can be left out using substring: s[:-3]+s[-2:] or string substitute.
So the final answer is as below.
from datetime import datetime
s = '2018-03-11 13:15:31.734874+01:00'
datetime.strptime(s[:-3]+s[-2:], '%Y-%m-%d %H:%M:%S.%f%z')
%Y %m %d  should be changed to %Y-%m-%d to match with the time string. Also, you need to remove the last : from the input to use with %z.
Here is how you should do:
import datetime
s = '2018-03-11 13:15:31.734874+01:00'
print(datetime.datetime.strptime(''.join(s.rsplit(':', 1)), '%Y-%m-%d %H:%M:%S.%f%z'))
# 2018-03-11 13:15:31.734874+01:00
At first:
%Y %m %d will not match 2018-03-11. You need to adapt it to the time string! %Y-%m-%d instead should work.
Secondly:
IF you are in python3, the %z was added for time stamps. However the timestamp has to be without the colon, e.g. +0100instead of +01:00. Therefore, if you use python3 this works:
>>> time_string = '2018-03-11 13:15:31.734874+01:00'
>>> time_string = ''.join(time_string.rsplit(':', 1))
>>> datetime.datetime.strptime(time_string, '%Y-%m-%d %H:%M:%S.%f%z')
datetime.datetime(2018, 3, 11, 13, 15, 31, 734874, tzinfo=datetime.timezone(datetime.timedelta(0, 3600)))
Btw the time_string after the editing looks like that:
>>> time_string
'2018-03-11 13:15:31.734874+0100'
IF you are in python2, the %z won't work, here you have to use the parse function of the dateutil module, which is straight forward.
>>> from dateutil.parser import parse
>>> parse('2018-03-11 13:15:31.734874+01:00')
datetime.datetime(2018, 3, 11, 13, 15, 31, 734874, tzinfo=tzoffset(None, 3600))

Convert String to Python datetime Object without Zero Padding

I'm using python 3.5.
I have a string formatted as mm/dd/yyyy H:MM:SS AM/PM that I would like as a python datetime object.
Here is what I've tried.
date = "09/10/2015 6:17:09 PM"
date_obj = datetime.datetime.strptime(date, '%d/%m/%Y %I:%M:%S %p')
But this gets an error because the hour is not zero padded. The formatting was done per the table on the
datetime documentation, which does not allow the hour to have one digit.
I've tried splitting the date up, adding a zero and then reassembling the string back together, while this works, this seems less robust/ideal.
date = "09/10/2015 6:17:09 PM"
date = date.split()
date = date[0] + " 0" + date[1] + " " + date[2]
Any recommendation on how to get the datetime object directly, or a better method for padding the hour would be helpful.
Thank you.
There is nothing wrong with this code:
>>> date = "09/10/2015 6:17:09 PM"
>>> date_obj = datetime.datetime.strptime(date, '%m/%d/%Y %I:%M:%S %p')
>>> date_obj
datetime.datetime(2015, 9, 10, 18, 17, 9)
>>> print(date_obj)
2015-09-10 18:17:09
The individual attributes of the datetime object are integers, not strings, and the internal representation uses 24hr values for the hour.
Note that I have swapped the day and month in the format strings as you state that the input format is mm/dd/yyyy.
But it seems that you actually want it as a string with zero padded hour, so you can use datetime.strftime() like this:
>>> date_str = date_obj.strftime('%m/%d/%Y %I:%M:%S %p')
>>> print(date_str)
09/10/2015 06:17:09 PM
# or, if you actually want the output format as %d/%m/%Y....
>>> print(date_obj.strftime('%d/%m/%Y %I:%M:%S %p'))
10/09/2015 06:17:09 PM

how to convert a datetime string back to datetime object?

I am storing a datetime string in a database. Now I face a problem. When I fetch the string from the database, I need to convert it back to a datetime object...
Any easy way to do that?
The string of datetime looks like:
2010-11-13 10:33:54.227806
You want datetime.strptime(date_string, format).
from datetime import datetime
datetime.strptime("2010-11-13 10:33:54.227806", "%Y-%m-%d %H:%M:%S.%f")
For details on the format string, see http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior
I sugggest you install python-dateutilt:
from dateutil import parser
d = parser.parse(yourstring)
This library gets a datetime object from your date-string in a 'smart' way...
# time tuple to datetime object
time_tuple = (2008, 11, 12, 13, 51, 18, 2, 317, 0)
dt_obj = datetime(*time_tuple[0:6])
print repr(dt_obj)
# date string to datetime object
date_str = "2008-11-10 17:53:59"
dt_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print repr(dt_obj)
# timestamp to datetime object in local time
timestamp = 1226527167.595983
dt_obj = datetime.fromtimestamp(timestamp)
print repr(dt_obj)

Categories

Resources