how to convert and subtract dates, times in python - python

I have the following date/time:
2011-09-27 13:42:16
I need to convert it to:
9/27/2011 13:42:16
I also need to be able to subtract one date from another and get the result in HH:MM:SS format. I have tried to use the dateutil.parser.parse function, and it parses the date fine but sadly it doesn't seem to get the time correctly. I also tried to use another method I found on stackoverflow that uses "time", but I get an error that time is not defined.

You can use datetime's strptime function:
from datetime import datetime
date = '2011-09-27 13:42:16'
result = datetime.strptime(date, '%Y-%m-%d %H:%M:%S')
You were lucky, as I had that above line written for a project of mine.
To print it back out, try strftime:
print result.strftime('%m/%d/%Y %H:%M:%S')

Use python-dateutil:
import dateutil.parser as dateparser
mydate = dateparser.parse("2011-09-27 13:42:16",fuzzy=True)
print(mydate.strftime('%m/%d/%Y T%H:%M:%S'))

http://docs.python.org/library/datetime.html#datetime.datetime.strptime
and
http://docs.python.org/library/datetime.html#datetime.datetime.strftime
(And the rest of the datetime module.)

Related

Datetime conversion generic approach

I have the following dates:
4/29/2020
5/7/2020
9/10/2020
10/5/2020
11/20/2020
The dates extracted from Oracle are correctly read as datetime objects in Python. However, when I manually add dates to the list in Excel, the program sees the date as string and crashes.
invalid input for query argument $1: '9/10/2020' (expected a datetime.date or datetime.datetime instance, got 'str')
This is what I am doing:
if isinstance(my_date,str):
my_date = date.fromisoformat(my_date)
It's not working. Is there a way to automatically convert a date in any format to datetime object? Thanks!
You can convert your code to something like this:
from datetime import datetime
if isinstance(my_date,str):
my_date = datetime.strptime(my_date, '%m/%d/%Y')
Yes there is : datetime.strptime
You can find documentation on how to use it here : https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

Converting date into '%Y-%m-%d' using strptime and strftime using Python

I have a .csv file with a date format I am unfamiliar with (I think from reading around it's unix).
1607299200000,string,int,float
1607385600000,string,int,float
1606953600000,string,int,float
I have been trying to convert it into '%Y-%m-%d' using Python but keep getting various errors. I am fairly novice with Python but this is what I have so far:
outRow.append(datetime.datetime.strptime(row[0],'%B %d %Y').strftime('%Y-%m-%d'))
Any help would be appreciated.
import datetime
timestamp = datetime.datetime.fromtimestamp(1500000000)
print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))
Output:
2017-07-14 08:10:00
The tricky part here is that you have a unix timestamp with microseconds.
AFAIK there's no option to convert unix ts with ms to datetime.
So first you have to drop them (div by 1000), then add them if needed.
ts = row[0]
dt = datetime.utcfromtimestamp(ts//1000).replace(microsecond=ts%1000*1000)
then you can strftime to whichever format you need.
Though if you need to execute this operation for the entire csv, you better look into pandas but that's out of the scope of this question.

Python3 date and time formatting

I'm using an API that sends a date in a wierd format "YYYY-MM-DDTHH:MM:SSZ".
So the date comes out as 2018-04-27T23:59:18Z, I have never seen a date and time formatted like this. Its a string and I would like to format it as MM-DD-YYYY HH:MM:SS. I can't even wrap my head around removing the T and Z. Any help would be appreciated! Thanks in advance!
Create datetime.datetime object from your string via datetime.strptime, then turn it back into a string with its strftime method.
>>> from datetime import datetime
>>> s = "2018-04-27T23:59:18Z"
>>> datetime.strptime(s, '%Y-%m-%dT%XZ').strftime('%m-%d-%Y %X')
>>> '04-27-2018 23:59:18'
strptime and strftime behavior
(Depending on you locale you might have to use %H, %M and %S instead of %X.)
That looks like the ISO 8601 time format.
For reasons that I really don't understand, there's no standard library function that parses ISO 8601 correctly. The dateutil package that you can find on PyPI will parse it for you though.
Use this pattern:
import datetime
d = '2018-04-27T23:59:18Z'
myDate = datetime.datetime.strptime(d, '%Y-%m-%dT%H:%M:%SZ')
# datetime.datetime(2018, 4, 27, 23, 59, 18)
Then to get a datetime string use strftime:
myDate_str = myDate.strftime('%Y-%m-%d %H:%M:%S')
# '2018-04-27 23:59:18'

Converting timestamp to unix date python

Here is how the timestamp looks -
2015-07-17 06:01:51.066141+00:00
I'm looking around to convert this to unix date time.
datetime.strptime("2015-07-17 06:01:51.066141+00:00", "%Y-%m-%d %H:%M:%S.%f%z").strftime("%s")
ValueError: 'z' is a bad directive in format '%Y-%m-%d %H:%M:%S.%f%z'
throws error for me, probably because of wrong format being used.
PS: my virtualenv is on python 2.7
ideas please ?
python 2.7 strptime() does not support z directive, either you can use python 3.2+ or some other 3rd party library like dateutil.
For Python 2.7 use arrow:
import arrow
date_str = "2015-07-17 06:01:51.066141+00:00"
unix_time = arrow.get(date_str).timestamp
On PY3 (verified on 3.4), using only standard libs
The date string you show will not be parsed by the standard python datetime library since it has a colon in the timezone (see here). The colon can be easily removed since it's always in the same position (or use rfind to find its index starting from the right). Your simplest solution is:
import datetime
date_str = "2015-07-17 06:01:51.066141+00:00"
date_str_no_colon = date_str[:-3]+date_str[-2:] # remove last colon
dt_obj = datetime.datetime.strptime(date_str_no_colon, "%Y-%m-%d %H:%M:%S.%f%z")
unix_time = dt_obj.timestamp()
Note that arrow should still work with PY3, and is a better solution in general- you don't want to get into datetime parsing wars with python. It will win.
The way to parse the date is not right. You'll either need to parse it by hand, find another library (for example the dateutil.parser.parse method that will parse your string directly without supplying format string) that supports that format or make the timestamp in another format. Even with newer versions of python the %z directive does not accept TZ offsets in the +/-HH:MM format (with colon).
As the source of the timestamp is django.DateTimeField maybe this question can help?
For converting to unix timestamp you seem to have to do some work since there does not seem to be a direct method for that:
(t - datetime.utcfromtimestamp(0)).total_seconds()
where t is the datetime (assuming it's in UTC and there is no tzinfo) you want to convert to POSIX timestamp. If the assumption is not correct you need to put tzinfo in the zero timestamp you subtract as shown below where the assumption does not hold.
If you want to use dateutil.parser the complete solution would be:
(dateutil.parser.parse(timestamp) - datetime.utcfromtimestamp(0).replace(tzinfo=utc()).total_seconds()
strptime() has no support for timezones.
So, you can make the conversion ignoring the timezone in the following way:
datetime.strptime("2015-07-17 06:01:51.066141", "%Y-%m-%d %I:%M:%S.%f").strftime("%s")
'1437102111'
Or in order to avoid using %s, as suggested below in the commments :
from datetime import datetime
(datetime.strptime("2015-07-17 06:01:51.066141", "%Y-%m-%d %I:%M:%S.%f") - datetime(1970, 1, 1)).total_seconds()
1437112911.066141
Notice this is a working version for Python 2, you can also check solutions for other versions here
Otherwise, you will have to use other libraries (django.utils or email.utils) that support timezones, or implement the timezone parsing on your own.
P.S. :
strptime docs appear to have support for timezone, but in fact it has not been implemented. Try :
datetime.strptime("2015-07-17 06:01:51.066141+00:00", "%Y-%m-%d %I:%M:%S.%f%z").strftime("%s")
and you will see that it is not supported. You can also verify it by searching more about strptime()
There are two parts:
to convert "2015-07-17 06:01:51.066141+00:00" into a datetime object that represents UTC time, see Convert timestamps with offset to datetime obj using strptime. Or If you know that the utc offset is always +0000:
from datetime import datetime
utc_time = datetime.strptime(time_string, "%Y-%m-%d %H:%M:%S.%f+00:00")
to convert the UTC time to POSIX timestamp (unix time), see Converting datetime.date to UTC timestamp in Python:
from datetime import datetime
timestamp = (utc_time - datetime(1970, 1, 1)).total_seconds()

Django - String to Date - Date to UNIX Timestamp

I need to convert a date from a string (entered into a url) in the form of 12/09/2008-12:40:49. Obviously, I'll need a UNIX Timestamp at the end of it, but before I get that I need the Date object first.
How do I do this? I can't find any resources that show the date in that format? Thank you.
You need the strptime method. If you're on Python 2.5 or higher, this is a method on datetime, otherwise you have to use a combination of the time and datetime modules to achieve this.
Python 2.5 up:
from datetime import datetime
dt = datetime.strptime(s, "%d/%m/%Y-%H:%M:%S")
below 2.5:
from datetime import datetime
from time import strptime
dt = datetime(*strptime(s, "%d/%m/%Y-%H:%M:%S")[0:6])
You can use the time.strptime() method to parse a date string. This will return a time_struct that you can pass to time.mktime() (when the string represents a local time) or calendar.timegm() (when the string is a UTC time) to get the number of seconds since the epoch.

Categories