convert str date to datetime for timezone - python

I have an API that return this date string
strdate = '2019-10-07T06:09:28.984Z'
How do I convert it to a datetime object?
dt = datetime.datetime.strptime(strdate, '%Y-%m-%d')
If I use strptime like above i get "ValueError: unconverted data remains: T06:09:54.346Z"
What do I do if there is "T" and "Z" included in the string date? I want the data in local time. But is the string really timezone aware so I can convert it properly? In this case I know the timezone, but what if I did not know?

The error is because you're not including the time part in the format string. Do that:
datetime.strptime('2019-10-07T06:09:28.984Z', '%Y-%m-%dT%H:%M:%S.%f%z')
This results in:
datetime.datetime(2019, 10, 7, 6, 9, 28, 984000, tzinfo=datetime.timezone.utc)
If you want to convert this to a local timezone, do that:
from pytz import timezone
dt = datetime.strptime(strdate, '%Y-%m-%dT%H:%M:%S.%f%z')
local_dt = dt.astimezone(timezone('Asia/Tokyo'))
Demo: https://repl.it/repls/RotatingSqueakyCertifications

import datetime
strdate = '2019-10-07T06:09:28.984Z'
dt=datetime.datetime.strptime(strdate, "%Y-%m-%dT%H:%M:%S.%fZ")
print(dt)
# output - 2019-10-07 06:09:28.984000

Related

Converting string (with timezone) to datetime in python

I aim to convert
stringtime = '2020-02-30 10:27:00+01:00'
so that I can compare it to
nowtime = datetime.datetime.utcnow()
using
if nowtime > stringtime:
print(1)
I tried strptime:
datetime.datetime.strptime(stringtime, '%Y-%m-%d %H:%M:%S')
But cannot find a format specification for the timezone in the strptime documentation.
I also tried
pandas.Timestamp(stringtime)
but I get ValueError: could not convert string to Timestamp.
How can this be done?
datetime.datetime.strptime(stringtime, '%Y-%m-%d %H:%M:%S%z')
Will give you the expected result %z is the format (Python3 only), however your original date is invalid as February doesnt have 30 days :)
First of all: Your stringtime is wrong, there exists no February 30th. ;)
You can achieve what you want with dateutil:
import dateutil.parser
stringtime = '2020-03-30 10:27:00+01:00'
dateutil.parser.isoparse(stringtime)
# datetime.datetime(2020, 3, 30, 10, 27, tzinfo=tzoffset(None, 3600))

Convert python timezone aware datetime string to utc time

I have a Python datetime string that is timezone aware and need to convert it to UTC timestamp.
'2016-07-15T10:00:00-06:00'
Most of the SO links talks about getting the current datetime in UTC but not on converting the given datetime to UTC.
Hi this was a bit tricky, but here is my, probably far from perfect, answer:
[IN]
import datetime
import pytz
date_str = '2016-07-15T10:00:00-06:00'
# Have to get rid of that bothersome final colon for %z to work
datetime_object = datetime.datetime.strptime(date_str[:-3] + date_str[-2:],
'%Y-%m-%dT%H:%M:%S%z')
datetime_object.astimezone(pytz.utc)
[OUT]
datetime.datetime(2016, 7, 15, 16, 0, tzinfo=<UTC>)

how do i store a return value in the format 2014-06-15 19:51:37 to a datetime variable in python?

I have done some researching and I believe I am supposed to use the datetime.datetime.fromtimestamp() method but I do not know exactly how to change a datetime in format 2014-06-15 19:51:37 to a variable usable in python where i can add and subtract and compare the dates.
You can use datetime.datetime.strptime. Specifically, the timeformat you will be using is '%Y-%m-%d %H:%M:%S'
e.g:
>>> import datetime
>>> date_str = '2014-06-15 19:51:37'
>>> datetime.datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')
datetime.datetime(2014, 6, 15, 19, 51, 37)

Django date YYYY-MM-DD

I get date in format(YYYY-MM-DD)
Then I want to add timedelta
mydate + timedelta(days=1)
and I get error
coercing to Unicode: need string or buffer, datetime.timedelta found
mydate is a string. Try doing this:
from datetime import datetime
parsed_date = datetime.strptime(mydate, "%Y-%m-%d")
new_date = parsed_date + timedelta(days=1)
Data sent by the client will be sent as a Unicode and you have to parse it on server side
datetime.strptime(date, '%Y-%m-%d')
If it's part of a form, the data should be reformatted automatically when cleaned (though you might need to configure the field to accept the format you expect).
You have to convert your string date to python datetime:
>>> from datetime import datetime, timedelta
>>> dt_str = "2013/10/11"
>>> dt = datetime.strptime(dt_str, "%Y/%m/%d")
>>> new_dt = dt + timedelta(days=1)
>>> print new_dt
datetime.datetime(2013, 10, 12, 0, 0)
If you now want to get the date as string:
>>> print new_dt.strftime("%Y/%m/%d")
'2013/10/12'

Convert string date to timestamp in Python

How to convert a string in the format "%d/%m/%Y" to timestamp?
"01/12/2011" -> 1322697600
>>> import time
>>> import datetime
>>> s = "01/12/2011"
>>> time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple())
1322697600.0
I use ciso8601, which is 62x faster than datetime's strptime.
t = "01/12/2011"
ts = ciso8601.parse_datetime(t)
# to get time in seconds:
time.mktime(ts.timetuple())
You can learn more here.
>>> int(datetime.datetime.strptime('01/12/2011', '%d/%m/%Y').strftime("%s"))
1322683200
To convert the string into a date object:
from datetime import date, datetime
date_string = "01/12/2011"
date_object = date(*map(int, reversed(date_string.split("/"))))
assert date_object == datetime.strptime(date_string, "%d/%m/%Y").date()
The way to convert the date object into POSIX timestamp depends on timezone. From Converting datetime.date to UTC timestamp in Python:
date object represents midnight in UTC
import calendar
timestamp1 = calendar.timegm(utc_date.timetuple())
timestamp2 = (utc_date.toordinal() - date(1970, 1, 1).toordinal()) * 24*60*60
assert timestamp1 == timestamp2
date object represents midnight in local time
import time
timestamp3 = time.mktime(local_date.timetuple())
assert timestamp3 != timestamp1 or (time.gmtime() == time.localtime())
The timestamps are different unless midnight in UTC and in local time is the same time instance.
Simply use datetime.datetime.strptime:
import datetime
stime = "01/12/2011"
print(datetime.datetime.strptime(stime, "%d/%m/%Y").timestamp())
Result:
1322697600
To use UTC instead of the local timezone use .replace:
datetime.datetime.strptime(stime, "%d/%m/%Y").replace(tzinfo=datetime.timezone.utc).timestamp()
The answer depends also on your input date timezone. If your date is a local date, then you can use mktime() like katrielalex said - only I don't see why he used datetime instead of this shorter version:
>>> time.mktime(time.strptime('01/12/2011', "%d/%m/%Y"))
1322694000.0
But observe that my result is different than his, as I am probably in a different TZ (and the result is timezone-free UNIX timestamp)
Now if the input date is already in UTC, than I believe the right solution is:
>>> calendar.timegm(time.strptime('01/12/2011', '%d/%m/%Y'))
1322697600
I would give a answer for beginners (like me):
You have the date string "01/12/2011". Then it can be written by the format "%d/%m/%Y". If you want to format to another format like "July 9, 2015", here a good cheatsheet.
Import the datetime library.
Use the datetime.datetime class to handle date and time combinations.
Use the strptime method to convert a string datetime to a object datetime.
Finally, use the timestamp method to get the Unix epoch time as a float. So,
import datetime
print( int( datetime.datetime.strptime( "01/12/2011","%d/%m/%Y" ).timestamp() ) )
# prints 1322712000
A lot of these answers don't bother to consider that the date is naive to begin with
To be correct, you need to make the naive date a timezone aware datetime first
import datetime
import pytz
# naive datetime
d = datetime.datetime.strptime('01/12/2011', '%d/%m/%Y')
>>> datetime.datetime(2011, 12, 1, 0, 0)
# add proper timezone
pst = pytz.timezone('America/Los_Angeles')
d = pst.localize(d)
>>> datetime.datetime(2011, 12, 1, 0, 0,
tzinfo=<DstTzInfo 'America/Los_Angeles' PST-1 day, 16:00:00 STD>)
# convert to UTC timezone
utc = pytz.UTC
d = d.astimezone(utc)
>>> datetime.datetime(2011, 12, 1, 8, 0, tzinfo=<UTC>)
# epoch is the beginning of time in the UTC timestamp world
epoch = datetime.datetime(1970,1,1,0,0,0,tzinfo=pytz.UTC)
>>> datetime.datetime(1970, 1, 1, 0, 0, tzinfo=<UTC>)
# get the total second difference
ts = (d - epoch).total_seconds()
>>> 1322726400.0
Also:
Be careful, using pytz for tzinfo in a datetime.datetime DOESN'T WORK for many timezones. See datetime with pytz timezone. Different offset depending on how tzinfo is set
# Don't do this:
d = datetime.datetime(2011, 12, 1,0,0,0, tzinfo=pytz.timezone('America/Los_Angeles'))
>>> datetime.datetime(2011, 1, 12, 0, 0,
tzinfo=<DstTzInfo 'America/Los_Angeles' LMT-1 day, 16:07:00 STD>)
# tzinfo in not PST but LMT here, with a 7min offset !!!
# when converting to UTC:
d = d.astimezone(pytz.UTC)
>>> datetime.datetime(2011, 1, 12, 7, 53, tzinfo=<UTC>)
# you end up with an offset
https://en.wikipedia.org/wiki/Local_mean_time
First you must the strptime class to convert the string to a struct_time format.
Then just use mktime from there to get your float.
I would suggest dateutil:
import dateutil.parser
dateutil.parser.parse("01/12/2011", dayfirst=True).timestamp()
Seems to be quite efficient:
import datetime
day, month, year = '01/12/2011'.split('/')
datetime.datetime(int(year), int(month), int(day)).timestamp()
1.61 µs ± 120 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
you can convert to isoformat
my_date = '2020/08/08'
my_date = my_date.replace('/','-') # just to adapte to your question
date_timestamp = datetime.datetime.fromisoformat(my_date).timestamp()
You can refer this following link for using strptime function from datetime.datetime, to convert date from any format along with time zone.
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
just use datetime.timestamp(your datetime instanse), datetime instance contains the timezone infomation, so the timestamp will be a standard utc timestamp. if you transform the datetime to timetuple, it will lose it's timezone, so the result will be error.
if you want to provide an interface, you should write like this:
int(datetime.timestamp(time_instance)) * 1000
A simple function to get UNIX Epoch time.
NOTE: This function assumes the input date time is in UTC format (Refer to comments here).
def utctimestamp(ts: str, DATETIME_FORMAT: str = "%d/%m/%Y"):
import datetime, calendar
ts = datetime.datetime.utcnow() if ts is None else datetime.datetime.strptime(ts, DATETIME_FORMAT)
return calendar.timegm(ts.utctimetuple())
Usage:
>>> utctimestamp("01/12/2011")
1322697600
>>> utctimestamp("2011-12-01", "%Y-%m-%d")
1322697600
You can go both directions, unix epoch <==> datetime :
import datetime
import time
the_date = datetime.datetime.fromtimestamp( 1639763585 )
unix_time = time.mktime(the_date.timetuple())
assert ( the_date == datetime.datetime.fromtimestamp(unix_time) ) & \
( time.mktime(the_date.timetuple()) == unix_time )

Categories