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

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

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'

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)

How to convert a string to datetime object [duplicate]

This question already has answers here:
How do I parse an ISO 8601-formatted date?
(29 answers)
Closed 5 years ago.
With the time value being:
value = '2017-08-31T02:24:29.000Z'
I try to convert it to a datetime object with:
import datetime
datetime_object = datetime.datetime.strptime(value, '%Y-%b-%d %I:%M%p')
But the command crashes with the exception:
ValueError: time data '2017-08-31T02:24:29.000Z' does not match format '%Y-%b-%d %I:%M%p'
You should be using a builtin Python's datautil module instead of date time:
import dateutil.parser
value = '2017-08-31T02:24:29.000Z'
result = dateutil.parser.parse(value)
First of all, you are missing the formatter for the microsecond.
Second of all, there is no second colon for dividing the minute and second.
Third, the %b operator is for the monthname (Jan,Feb,etc.). You want to use %m.
Final format is '%Y-%m-%dT%I:%M:%S.%fZ'.
This is your code:
datetime_object = datetime.datetime.strptime(value, '%Y-%m-%dT%I:%M:%S.%fZ')
You should get 2017-08-31 02:24:29 as the value of datetime_object.

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

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

convert string to date type python [duplicate]

This question already has answers here:
Python date string to date object
(9 answers)
Closed 9 years ago.
How do I convert a string to a date object in python?
The string would be: "30-01-12" (corresponding to the format: "%d-%m-%y")
I don't want a datetime.datetime object, but rather a datetime.date
You still use datetime.datetime but then request just the .date() portion:
datetime.datetime.strptime('30-01-12', '%d-%m-%y').date()
Demonstration:
>>> import datetime
>>> datetime.datetime.strptime('30-01-12', '%d-%m-%y').date()
datetime.date(2012, 1, 30)
This should work:
import datetime
s = "30-01-12"
slist = s.split("-")
sdate = datetime.date(int(slist[2]),int(slist[0]),int(slist[1]))
from datetime import datetime,date
date_str = '30-01-12'
formatter_string = "%d-%m-%y"
datetime_object = datetime.strptime(date_str, formatter_string)
date_object = datetime_object.date()

Categories