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)
Related
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)
I am extracting Data from Mongodb using some date filter. In mongo my date is in ISO format . As i am dynamically adding date from some variable which is in timestamp format(2019-07-15 14:54:53).Getting Empty Result
curs = col1.aggregate([{'$match':{update_col: {'$gte': last_updt }}},{'$project':json_acceptable_string}])
I am expecting Rows after filtering but acual its giving empty dataset
you can use datetime.strptime to parse the original string to a datetime object, then use datetime.isoformat to get it in ISO format.
try this:
import datetime
original_date = '2019-07-15 14:54:53'
date_obj = datetime.datetime.strptime(original_date, "%Y-%m-%d %H:%M:%S")
iso_date = date_obj.isoformat()
print(iso_date)
try this
from dateutil import parser as date_parser
dt_obj = date_parser.parse('2019-07-15 14:54:53')
where dt_obj is an object of standard datetime.datetime class
You can use fromisoformat.
Try
from datetime import datetime
iso_string = '2019-07-15 14:54:53'
you_date_obj = datetime.fromisoformat(iso_string)
I have data with the date format as follows:
date_format = 190410
year = 19
month = 04
date = 10
I want to change the date format, to be like this:
date_format = 10-04-2019
How do I solve this problem?
>>> import datetime
>>> date = 190410
>>> datetime.datetime.strptime(str(date), "%y%m%d").strftime("%d-%m-%Y")
'10-04-2019'
datetime.strptime() takes a data string and a format, and turns that into datetime object, and datetime objects have a method called strftime that turns datetime objects to string with given format. You can look what %y %m %d %Y are from here.
This is what you want(Notice that you have to change your format)
import datetime
date_format = '2019-04-10'
date_time_obj = datetime.datetime.strptime(date_format, '%Y-%m-%d')
print(date_time_obj)
Here is an other example
import datetime
date_time_str = '2018-06-29 08:15:27.243860'
date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')
print('Date:', date_time_obj.date())
print('Time:', date_time_obj.time())
print('Date-time:', date_time_obj)
You can also do this
from datetime import datetime, timedelta
s = "20120213"
# you could also import date instead of datetime and use that.
date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))
print(date)
There are many ways to achieve what you want.
from datetime import datetime, timedelta
api_time = datetime.strptime(parsed_json["result"]["parameters"]["time"], "%H:%M:%S")
What I'm getting in api_time after debugging is 900-01-01 12:30:22. What I want is 12:30:22 only. I have checked other docs and .strptime should have done it but it didn't work.
Method 1: Strip space
One quick solution, if your input doesn't change.
from datetime import datetime, timedelta
api_time = datetime.strptime("1900-01-01 12:30:22".split(" ")[1], "%H:%M:%S")
print api_time
>1900-01-01 12:30:22
In your case:
api_time = datetime.strptime(parsed_json["result"]["parameters"]["time"], "%H:%M:%S")
Method 2: Construct datetime
Or you can just construct your datetime object and then access it's second, minute, hour attributes as follows:
from datetime import datetime, timedelta
api_time = datetime.strptime("1900-01-01 12:30:22", "%Y-%m-%d %H:%M:%S")
print "{0}:{1}:{2}".format(api_time.second, api_time.minute, api_time.hour)
>22:30:12
You can convert them from datetime to string, then just use string split:
a = '1900-01-01 12:30:22'
a.split(' ')[1]
-->
from datetime import datetime
api_time = datetime(1900, 01, 01, 12, 30, 22).strftime("%Y-%m-%d %H:%M:%S")
api_time.split(' ')[1]
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'