How to convert API timestamp into python datetime object [duplicate] - python

This question already has answers here:
How do I parse an ISO 8601-formatted date?
(29 answers)
Closed 8 years ago.
I am getting the following string from an API call:
s = '2014-12-11T20:46:12Z'
How would I then convert this into a python object? Is there an easy way, or should I be splitting up the string, for example:
year = s.split('-')[0]
month = s.split('-')[1]
day = s.split('-')[2]
time = s.split('T')[1]
...etc...

You can use the datetime.datetime.strptime function:
>>> from datetime import datetime
>>> s = '2014-12-11T20:46:12Z'
>>> datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ')
datetime.datetime(2014, 12, 11, 20, 46, 12)
>>>
For a complete list of the available format codes, see strftime() and strptime() Behavior.

Using datetime should do it, recently I found arrow is also a good library to deal with dates.
import arrow
s = '2014-12-11T20:46:12Z'
your_date = arrow.get(s)
print(t.year) # 2014
print(t.hour) # 20

Related

Convert date string format to a datetime Python Object [duplicate]

This question already has answers here:
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 2 years ago.
i've one doubt.
I'm doing request to an API which return me event date. I was hope that date will be a timestamp, but i get this value:
{"date":"2020-08-24T21:15:00+00:00"}
I want to get a python datetime object.
How can I do that?
from datetime import datetime
dates = {"date":"2020-08-24T21:15:00+00:00"}
date = dates.get("date")
day = datetime.strptime(date, "%Y-%m-%dT%H:%M:%S+00:00")
Your looking for strptime.
Heres a good article:
https://www.programiz.com/python-programming/datetime/strptime
Use dateutil.parser which smartly parse date string:
import json
import dateutil.parser
result = '{"date":"2020-08-24T21:15:00+00:00"}'
x = json.loads(result)
dt = dateutil.parser.parse(x['date'])
# 2020-08-24 21:15:00+00:00
print(dt)
# <class 'datetime.datetime'>
print(type(dt))
I think you can do it respecting the format while parsing the string:
You have to try to follow the structure of the string and assign each value to the correct time value. For example:
str = '2018-06-29 08:15:27.243860'
time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')
Note that your case is pretty different.
It could be similar to '%Y-%m-%dT%H:%M:%S.f'

How to convert a string with timezone to unix timestamp python? [duplicate]

This question already has answers here:
Convert timestamps with offset to datetime obj using strptime
(4 answers)
How do I parse an ISO 8601-formatted date?
(29 answers)
Closed 2 years ago.
I have a datetime string I get from a database and I want to convert it to unix timestamp.
I am not sure what is the way to do it.
db_timestamp = '2020-08-05 12:48:50+02:00'
f = '%Y-%m-%d %H:%M:%S%z'
timestamp = datetime.strptime(db_timestamp , f)
TypeError: strptime() argument 1 must be str, not datetime.datetime
Another way I tried was as following
python_timestamp = datetime.isoformat(db_timestamp)
test_timestamp = datetime.strptime(python_timestamp , f)
Then I get the following error
ValueError: time data '2020-08-05T12:48:50+02:00' does not match format '%Y-%m-%d %H:%M:%S%z'
How to fix this error?
What should be the correct string format for db_timestamp?
assuming you run Python 3.7 or higher, what you want is fromisoformat to parse the string and timestamp() to get seconds since the epoch UNIX time (POSIX).
from datetime import datetime
db_timestamp = '2020-08-05 12:48:50+02:00'
# to datetime object:
dt = datetime.fromisoformat(db_timestamp)
# to UNIX time:
ts = dt.timestamp()
print(repr(dt), ts)
>>> datetime.datetime(2020, 8, 5, 12, 48, 50, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200))) 1596624530.0

Python Convert date to datetime directly [duplicate]

This question already has answers here:
Convert date to datetime in Python
(14 answers)
Closed 2 years ago.
In Python, I convert a date to datetime by:
converting from date to string
converting from string to datetime
Code:
import datetime
dt_format="%d%m%Y"
my_date = datetime.date.today()
datetime.datetime.strptime(my_date.strftime(dt_format), dt_format)
I suspect this is far from the most efficient way to do this. What is the most efficient way to convert a date to datetime in Python?
Use datetime.datetime.combine() with a time object, datetime.time.min represents 00:00 and would match the output of your date-string-datetime path:
datetime.datetime.combine(my_date, datetime.time.min)
Demo:
>>> import datetime
>>> my_date = datetime.date.today()
>>> datetime.datetime.combine(my_date, datetime.time.min)
datetime.datetime(2013, 3, 27, 0, 0)
Alternatively, as suggested here, this might be more readable:
datetime(date.year, date.month, date.day)

date from string to datetime.date in python [duplicate]

This question already has answers here:
Python date string to date object
(9 answers)
Closed 9 years ago.
Can this be done any way more pythonic?
>>> import datetime
>>> date = '20131018'
>>> date
'20131018'
>>> year, month, day = date[0:4], date[4:6], date[6:]
>>> datetime.date(int(year), int(month), int(day))
datetime.date(2013, 10, 18)
Thanks
Python already has a built-in way of parsing dates from strings in the datetime package, namely datetime.datetime.strptime:
>>> from datetime import datetime as dt
>>> date = '20131018'
>>> dt.strptime(date, "%Y%m%d").date()
datetime.date(2013, 10, 18)
See the docs for all of the available format / parsing options.

Convert string into datetime type [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Convert Date String to DateTime Object in Python
Is there an easy way to convert the string the string 10/22/1984 into a datetime.date object?
You can use datetime.strptime method for this purpose:
from datetime import datetime
dVal = datetime.strptime('10/22/1984', '%m/%d/%Y')
You can read more using the following link that describes python strptime behavior.
Yes.
>>> datetime.datetime.strptime("10/22/1984", "%m/%d/%Y")
datetime.datetime(1984, 10, 22, 0, 0)
I'm sure there are many easy ways. Here is one:
import re
import datetime
my_date = '10/22/1984'
date_components = re.compile(r'(?P<month>\d+)/(?P<day>\d+)/(?P<year>\d+)')
matched_date_components = date_components.match(my_date)
date_time_object = datetime.date(year=matched_date_components.year,
month=matched_date_components.month,
day=matched_date_components.day)
first import datetime and then try in will work.
from datetime import datetime
date = datetime.strptime('10/22/1984', '%d/%m/%y')

Categories