Django - String to Date - Date to UNIX Timestamp - python

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.

Related

How to convert str time to timestamp?

I have a string "15:15:00"
I need to convert it to timestamp like 1410748201
Python
A UNIX timestamp always needs a relation between a date and a time to actually form it, since it is the number of seconds that are passed since 1970-01-01 00:00. Therefore I would recommend you to use the datetime module.
Let's assume you have given the following format: "2022-10-31 15:15:00".
With datetime you can convert the string into a datetime object by using the strptime() function.
Afterwards, a datetime object gives you the ability to convert your datetime into a UNIX timestamp with the timestamp() method of your datetime object.
from datetime import datetime
datetime_str = "2022-10-31 15:15:00"
datetime_obj = datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S")
print(datetime_obj.timestamp())

how can I convert date(YYYY, MM, DD) format to YYYY/MM/DD with python? [duplicate]

This question already has answers here:
Convert datetime object to a String of date only in Python
(15 answers)
Closed 4 months ago.
I have a JSON that returns a date in the following date format:
datetime(2015, 12, 1)
So the key value from JSON is
'CreateDate': datetime(2015, 1, 1)
In order to be able to subtract two dates, I need to convert above to date format:
YYYY/MM/DD
so in above case that would become: 2015/12/01
Is there a smart way to do that? Is it at all possible? Or do I really have to parse it as a block of text? I tried using datetime.strptime, but I can't get it to work.
datetime(2015,12,1).strftime("%Y/%m/%d")
will do the trick for you. A complete python program would look like this.
# import the datetime and date classes from the datetime module
from datetime import datetime, date
# create your datetime(..) instance from your JSON somehow
# The included Python JSON tools do not usually know about date-times,
# so this may require a special step
# Assume you have a datetime now
dt = datetime(2015,12,1)
# Print it out in your format
print( dt.strftime("%Y/%m/%d") )
Two important details:
You are using just a date in a Python datetime. Nothing wrong with that but just note that the Python datetime module also has a date class
You can enable your JSON encoder/decoder to recognise dates and datetimes automatically but it requires extra work.
Now, to subtract datetimes from each other they should remain as instances of the datetime class. You can not subtract datetimes from each other once they have been formatted as a string.
Once you subtract a Python datetime from an other datetime the result will be an instance of the timedelta class.
from datetime import datetime, timedelta
# time_diff here is a timedelta type
time_diff = datetime(2015,12,1) - datetime(2014,11,1)
Now you can look up the Python timedelta type and extract the days, hours, minutes etc. that you need. Be aware that timedeltas can be a negative if you subtract a later datetime from an earlier one.
The datetime module has a function for doing this which is pretty easy as shown below
from datetime import datetime
print(datetime(2015,12,1).strftime("%Y/%m/%d"))
Also read more about the module here https://docs.python.org/3/library/datetime.html

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()

What is the easiest way to get current GMT time in Unix timestamp format?

Python provides different packages (datetime, time, calendar) as can be seen here in order to deal with time. I made a big mistake by using the following to get current GMT time time.mktime(datetime.datetime.utcnow().timetuple())
What is a simple way to get current GMT time in Unix timestamp?
I would use time.time() to get a timestamp in seconds since the epoch.
import time
time.time()
Output:
1369550494.884832
For the standard CPython implementation on most platforms this will return a UTC value.
import time
int(time.time())
Output:
1521462189
Does this help?
from datetime import datetime
import calendar
d = datetime.utcnow()
unixtime = calendar.timegm(d.utctimetuple())
print unixtime
How to convert Python UTC datetime object to UNIX timestamp
python2 and python3
it is good to use time module
import time
int(time.time())
1573708436
you can also use datetime module, but when you use strftime('%s'), but strftime convert time to your local time!
python2
from datetime import datetime
datetime.utcnow().strftime('%s')
python3
from datetime import datetime
datetime.utcnow().timestamp()
Python 3 seconds with microsecond decimal resolution:
from datetime import datetime
print(datetime.now().timestamp())
Python 3 integer seconds:
print(int(datetime.now().timestamp()))
WARNING on datetime.utcnow().timestamp()!
datetime.utcnow() is a non-timezone aware object. See reference: https://docs.python.org/3/library/datetime.html#aware-and-naive-objects
For something like 1am UTC:
from datetime import timezone
print(datetime(1970,1,1,1,0,tzinfo=timezone.utc).timestamp())
or
print(datetime.fromisoformat('1970-01-01T01:00:00+00:00').timestamp())
if you remove the tzinfo=timezone.utc or +00:00, you'll get results dependent on your current local time. Ex: 1am on Jan 1st 1970 in your current timezone - which could be legitimate - for example, if you want the timestamp of the instant when you were born, you should use the timezone you were born in. However, the timestamp from datetime.utcnow().timestamp() is neither the current instant in local time nor UTC. For example, I'm in GMT-7:00 right now, and datetime.utcnow().timestamp() gives a timestamp from 7 hours in the future!
Or just simply using the datetime standard module
In [2]: from datetime import timezone, datetime
...: int(datetime.now(tz=timezone.utc).timestamp() * 1000)
...:
Out[2]: 1514901741720
You can truncate or multiply depending on the resolution you want. This example is outputting millis.
If you want a proper Unix timestamp (in seconds) remove the * 1000
At least in python3, this works:
>>> datetime.strftime(datetime.utcnow(), "%s")
'1587503279'
I like this method:
import datetime, time
dts = datetime.datetime.utcnow()
epochtime = round(time.mktime(dts.timetuple()) + dts.microsecond/1e6)
The other methods posted here are either not guaranteed to give you UTC on all platforms or only report whole seconds. If you want full resolution, this works, to the micro-second.
from datetime import datetime as dt
dt.utcnow().strftime("%s")
Output:
1544524990
#First Example:
from datetime import datetime, timezone
timstamp1 =int(datetime.now(tz=timezone.utc).timestamp() * 1000)
print(timstamp1)
Output: 1572878043380
#second example:
import time
timstamp2 =int(time.time())
print(timstamp2)
Output: 1572878043
Here, we can see the first example gives more accurate time than second one.
Here I am using the first one.

how to convert and subtract dates, times in 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.)

Categories