Python add days in epoch time - python

How to add days in epoch time in Python
#lssec -a lastupdate -s root -f /etc/security/passwd 2>/dev/null | cut -f2 -d=
1425917335
above command giving me epoch time I want to add 90 days in that time. how do I add days in epoch time?

datetime makes it easy between fromtimestamp, timedelta and timestamp:
>>> import datetime
>>> orig = datetime.datetime.fromtimestamp(1425917335)
>>> new = orig + datetime.timedelta(days=90)
>>> print(new.timestamp())
1433693335.0
On Python 3.2 and earlier, datetime objects don't have a .timestamp() method, so you must change the last line to the less efficient two-stage conversion:
>>> import time
>>> print(time.mktime(new.timetuple()))
The two-stage conversion takes ~10x longer than .timestamp() on my machine, taking ~2.5 µs, vs. ~270 ns for .timestamp(); admittedly still trivial if you aren't doing it much, but if you need to do it a lot, consider it another argument for using modern Python. :-)

If the input is POSIX timestamp then to get +90 days:
DAY = 86400 # POSIX day (exact value)
future_time = epoch_time + 90*DAY
If you want to work with datetime objects then use UTC timezone:
from datetime import datetime, timedelta
utc_time = datetime.utcfromtimestamp(epoch_time)
future_time = utc_time + timedelta(90)
Don't use local time for the date/time arithmetic (avoid naive fromtimestamp(), mktime(), naive_dt.timestamp() if you can help it). To understand when it may fail, read Find if 24 hrs have passed between datetimes - Python.

You can you dateutil.parser as well:
since24Hours = datetime.utcnow() - timedelta(days=1)
since24Hours=dateutil.parser.parse(str(since24Hours))
since24Hours = since24Hours.strftime('%s')
since24Hours=int(since24Hours)*1000

Related

Epoch time `date +%s` equivalent in python [duplicate]

Does time.time() in the Python time module return the system's time or the time in UTC?
The time.time() function returns the number of seconds since the epoch, as a float. Note that "the epoch" is defined as the start of January 1st, 1970 in UTC. So the epoch is defined in terms of UTC and establishes a global moment in time. No matter where on Earth you are, "seconds past epoch" (time.time()) returns the same value at the same moment.
Here is some sample output I ran on my computer, converting it to a string as well.
>>> import time
>>> ts = time.time()
>>> ts
1355563265.81
>>> import datetime
>>> datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
'2012-12-15 01:21:05'
>>>
The ts variable is the time returned in seconds. I then converted it to a human-readable string using the datetime library.
This is for the text form of a timestamp that can be used in your text files. (The title of the question was different in the past, so the introduction to this answer was changed to clarify how it could be interpreted as the time. [updated 2016-01-14])
You can get the timestamp as a string using the .now() or .utcnow() of the datetime.datetime:
>>> import datetime
>>> print datetime.datetime.utcnow()
2012-12-15 10:14:51.898000
The now differs from utcnow as expected -- otherwise they work the same way:
>>> print datetime.datetime.now()
2012-12-15 11:15:09.205000
You can render the timestamp to the string explicitly:
>>> str(datetime.datetime.now())
'2012-12-15 11:15:24.984000'
Or you can be even more explicit to format the timestamp the way you like:
>>> datetime.datetime.now().strftime("%A, %d. %B %Y %I:%M%p")
'Saturday, 15. December 2012 11:19AM'
If you want the ISO format, use the .isoformat() method of the object:
>>> datetime.datetime.now().isoformat()
'2013-11-18T08:18:31.809000'
You can use these in variables for calculations and printing without conversions.
>>> ts = datetime.datetime.now()
>>> tf = datetime.datetime.now()
>>> te = tf - ts
>>> print ts
2015-04-21 12:02:19.209915
>>> print tf
2015-04-21 12:02:30.449895
>>> print te
0:00:11.239980
Based on the answer from #squiguy, to get a true timestamp I would type cast it from float.
>>> import time
>>> ts = int(time.time())
>>> print(ts)
1389177318
At least that's the concept.
The answer could be neither or both.
neither: time.time() returns approximately the number of seconds elapsed since the Epoch. The result doesn't depend on timezone so it is neither UTC nor local time. Here's POSIX defintion for "Seconds Since the Epoch".
both: time.time() doesn't require your system's clock to be synchronized so it reflects its value (though it has nothing to do with local timezone). Different computers may get different results at the same time. On the other hand if your computer time is synchronized then it is easy to get UTC time from the timestamp (if we ignore leap seconds):
from datetime import datetime
utc_dt = datetime.utcfromtimestamp(timestamp)
On how to get timestamps from UTC time in various Python versions, see How can I get a date converted to seconds since epoch according to UTC?
To get a local timestamp using datetime library, Python 3.x
#wanted format: year-month-day hour:minute:seconds
from datetime import datetime
# get time now
dt = datetime.now()
# format it to a string
timeStamp = dt.strftime('%Y-%m-%d %H:%M:%S')
# print it to screen
print(timeStamp)
I eventually settled for:
>>> import time
>>> time.mktime(time.gmtime())
1509467455.0
There is no such thing as an "epoch" in a specific timezone. The epoch is well-defined as a specific moment in time, so if you change the timezone, the time itself changes as well. Specifically, this time is Jan 1 1970 00:00:00 UTC. So time.time() returns the number of seconds since the epoch.
timestamp is always time in utc, but when you call datetime.datetime.fromtimestamp it returns you time in your local timezone corresponding to this timestamp, so result depend of your locale.
>>> import time, datetime
>>> time.time()
1564494136.0434234
>>> datetime.datetime.now()
datetime.datetime(2019, 7, 30, 16, 42, 3, 899179)
>>> datetime.datetime.fromtimestamp(time.time())
datetime.datetime(2019, 7, 30, 16, 43, 12, 4610)
There exist nice library arrow with different behaviour. In same case it returns you time object with UTC timezone.
>>> import arrow
>>> arrow.now()
<Arrow [2019-07-30T16:43:27.868760+03:00]>
>>> arrow.get(time.time())
<Arrow [2019-07-30T13:43:56.565342+00:00]>
time.time() return the unix timestamp.
you could use datetime library to get local time or UTC time.
import datetime
local_time = datetime.datetime.now()
print(local_time.strftime('%Y%m%d %H%M%S'))
utc_time = datetime.datetime.utcnow()
print(utc_time.strftime('%Y%m%d %H%M%S'))

In Python, compare a specific time on a day with the current time in epoch

I am attempting to compare the current time (A) to a certain time (B) on the current day. Subsequently, based on the result of that comparison, I want to return the POSIX time for a specific time, either tomorrow (C) or the day after tomorrow (D).
To illustrate, an example:
Suppose we have the current time (A) to be 12:00.
I want to compare that to (B), which is 20:00 today.
Since A < B, I want to return 13:00 tomorrow, formatted as a POSIX time.
Another example:
Now suppose the current time (A) is 21:00.
I still want to compare that to (B), which is 20:00 today.
Since A > B, I want to return 13:00 the day after tomorrow, again formatted as a POSIX time.
I've been trying to make this work using the timeand datetime libraries, but when using time I have a hard time finding B and when using datetime I can't find a way to return C and D as a POSIX time.
Have I correctly identified which libraries I should use and if so, what am I missing?
There are two questions:
Find whether you need "13:00 tomorrow" or "13:00 the day after tomorrow" depending on the current time relative to 20:00
Convert the result e.g., "13:00 tomorrow" to POSIX time
The first one is simple:
#!/usr/bin/env python
import datetime as DT
current_time = DT.datetime.now()
one_or_two = 1 if current_time.time() < DT.time(20, 0) else 2
target_date = current_time.date() + DT.timedelta(days=one_or_two)
target_time = DT.datetime.combine(target_date, DT.time(13, 0))
Note: 00:00 is considered to be less than 20:00. You might want to use time intervals instead e.g., 20:00-8:00 vs. 8:00-20:00, to find out whether the current time is in between.
The second question is essentially the same as How do I convert local time to UTC in Python? In the general case, there is no exact answer e.g., the same local time may occur twice or it may be missing completely—what answer to use depends on the specific application. See more details in my answer to python converting string in localtime to UTC epoch timestamp.
To get the correct result taking into account possible DST transitions or other changes in the local UTC offset between now and the target time (e.g., "the day after tomorrow"):
import pytz # $ pip install pytz
import tzlocal # $ pip install tzlocal
epoch = DT.datetime(1970,1,1, tzinfo=pytz.utc)
local_timezone = tzlocal.getlocalzone()
timezone_aware_dt = local_timezone.localize(target_time, is_dst=None)
posix_time = (timezone_aware_dt - epoch).total_seconds()
Note: is_dst=None is used to assert that the given local time exists and unambiguous e.g., there is no DST transitions at 13:00 in your local time.
If time.mktime() has access to a historical timezone database on your platform (or you just don't care about changes in the local utc offset) then you could find the "epoch" time using only stdlib:
import time
unix_time = time.mktime(target_time.timetuple())
You can read more details on when it fails and how to workaround it in Find if 24 hrs have passed between datetimes - Python.
Or more than you probably wanted to know about finding POSIX timestamp in Python can be found in Converting datetime.date to UTC timestamp in Python.
import datetime
A = datetime.datetime.now()
# A = A.replace(hour=21, minute=5) # This line simlulates "after 21:00"
B = A.replace(hour=20, minute=0, second=0, microsecond=0) # 20:00 today
if A < B:
print A.replace(hour=13, minute=0, second=0, microsecond=0) + datetime.timedelta(days=1) # 13:00 tomorrow
else:
print A.replace(hour=13, minute=0, second=0, microsecond=0) + datetime.timedelta(days=2) # 13:00 the day after
in Python 3 you can then return
X.timestamp()
in Python 2 you can use
def timestamp(dt):
return (dt - datetime.datetime(1970, 1, 1)).total_seconds()
timestamp(X)

How to get UTC time in Python?

How do I get the UTC time, i.e. milliseconds since Unix epoch on Jan 1, 1970?
For Python 2 code, use datetime.utcnow():
from datetime import datetime
datetime.utcnow()
For Python 3, use datetime.now(timezone.utc) (the 2.x solution will technically work, but has a giant warning in the 3.x docs):
from datetime import datetime, timezone
datetime.now(timezone.utc)
For your purposes when you need to calculate an amount of time spent between two dates all that you need is to subtract end and start dates. The results of such subtraction is a timedelta object.
From the python docs:
class datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
And this means that by default you can get any of the fields mentioned in it's definition -
days, seconds, microseconds, milliseconds, minutes, hours, weeks. Also timedelta instance has total_seconds() method that:
Return the total number of seconds contained in the duration.
Equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) *
106) / 106 computed with true division enabled.
Timezone-aware datetime object, unlike datetime.utcnow():
from datetime import datetime,timezone
now_utc = datetime.now(timezone.utc)
Timestamp in milliseconds since Unix epoch:
datetime.now(timezone.utc).timestamp() * 1000
In the form closest to your original:
import datetime
def UtcNow():
now = datetime.datetime.utcnow()
return now
If you need to know the number of seconds from 1970-01-01 rather than a native Python datetime, use this instead:
return (now - datetime.datetime(1970, 1, 1)).total_seconds()
Python has naming conventions that are at odds with what you might be used to in Javascript, see PEP 8. Also, a function that simply returns the result of another function is rather silly; if it's just a matter of making it more accessible, you can create another name for a function by simply assigning it. The first example above could be replaced with:
utc_now = datetime.datetime.utcnow
import datetime
import pytz
# datetime object with timezone awareness:
datetime.datetime.now(tz=pytz.utc)
# seconds from epoch:
datetime.datetime.now(tz=pytz.utc).timestamp()
# ms from epoch:
int(datetime.datetime.now(tz=pytz.utc).timestamp() * 1000)
Timezone aware with zero external dependencies:
from datetime import datetime, timezone
def utc_now():
return datetime.utcnow().replace(tzinfo=timezone.utc)
From datetime.datetime you already can export to timestamps with method strftime. Following your function example:
import datetime
def UtcNow():
now = datetime.datetime.utcnow()
return int(now.strftime("%s"))
If you want microseconds, you need to change the export string and cast to float like: return float(now.strftime("%s.%f"))
you could use datetime library to get UTC time even local time.
import datetime
utc_time = datetime.datetime.utcnow()
print(utc_time.strftime('%Y%m%d %H%M%S'))
why all reply based on datetime and not time?
i think is the easy way !
import time
nowgmt = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
print(nowgmt)
To be correct, UTC format needs at least the T letter:
>>> a=(datetime.datetime.now(timezone.utc))
>>> a.strftime("%Y-%m-%dT%H:%M:%SZ")
'2022-11-28T16:42:17Z'

In Python, how do you convert a `datetime` object to seconds?

I have a bunch of datetime objects and I want to calculate the number of seconds since a fixed time in the past for each one (for example since January 1, 1970).
import datetime
t = datetime.datetime(2009, 10, 21, 0, 0)
This seems to be only differentiating between dates that have different days:
t.toordinal()
How does one convert a datetime object to seconds?
For the special date of January 1, 1970 there are multiple options.
For any other starting date you need to get the difference between the two dates in seconds. Subtracting two dates gives a timedelta object, which as of Python 2.7 has a total_seconds() function.
>>> (t-datetime.datetime(1970,1,1)).total_seconds()
1256083200.0
The starting date is usually specified in UTC, so for proper results the datetime you feed into this formula should be in UTC as well. If your datetime isn't in UTC already, you'll need to convert it before you use it, or attach a tzinfo class that has the proper offset.
As noted in the comments, if you have a tzinfo attached to your datetime then you'll need one on the starting date as well or the subtraction will fail; for the example above I would add tzinfo=pytz.utc if using Python 2 or tzinfo=timezone.utc if using Python 3.
Starting from Python 3.3 this becomes super easy with the datetime.timestamp() method. This of course will only be useful if you need the number of seconds from 1970-01-01 UTC.
from datetime import datetime
dt = datetime.today() # Get timezone naive now
seconds = dt.timestamp()
The return value will be a float representing even fractions of a second. If the datetime is timezone naive (as in the example above), it will be assumed that the datetime object represents the local time, i.e. It will be the number of seconds from current time at your location to 1970-01-01 UTC.
To get the Unix time (seconds since January 1, 1970):
>>> import datetime, time
>>> t = datetime.datetime(2011, 10, 21, 0, 0)
>>> time.mktime(t.timetuple())
1319148000.0
Maybe off-the-topic: to get UNIX/POSIX time from datetime and convert it back:
>>> import datetime, time
>>> dt = datetime.datetime(2011, 10, 21, 0, 0)
>>> s = time.mktime(dt.timetuple())
>>> s
1319148000.0
# and back
>>> datetime.datetime.fromtimestamp(s)
datetime.datetime(2011, 10, 21, 0, 0)
Note that different timezones have impact on results, e.g. my current TZ/DST returns:
>>> time.mktime(datetime.datetime(1970, 1, 1, 0, 0).timetuple())
-3600 # -1h
therefore one should consider normalizing to UTC by using UTC versions of the functions.
Note that previous result can be used to calculate UTC offset of your current timezone. In this example this is +1h, i.e. UTC+0100.
References:
datetime.date.timetuple
time.mktime
datetime.datetime.fromtimestamp
introduction in time module explains POSIX time, 1970 epoch, UTC, TZ, DST ...
int (t.strftime("%s")) also works
from the python docs:
timedelta.total_seconds()
Return the total number of seconds contained in the duration. Equivalent to
(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
computed with true division enabled.
Note that for very large time intervals (greater than 270 years on most platforms) this method will lose microsecond accuracy.
This functionality is new in version 2.7.
Comparing the 4 most common ways to do this, for accuracy:
Method 1: Manual Calculation
from datetime import datetime
total1 = int(datetimeobj.strftime('%S'))
total1 += int(datetimeobj.strftime('%M')) * 60
total1 += int(datetimeobj.strftime('%H')) * 60 * 60
total1 += (int(datetimeobj.strftime('%j')) - 1) * 60 * 60 * 24
total1 += (int(datetimeobj.strftime('%Y')) - 1970) * 60 * 60 * 24 * 365
print ("Method #1: Manual")
print ("Before: %s" % datetimeobj)
print ("Seconds: %s " % total1)
print ("After: %s" % datetime.fromtimestamp(total1))
Output:
Method #1: Manual
Before: 1970-10-01 12:00:00
Seconds: 23630400
After: 1970-10-01 16:00:00
Accuracy test: FAIL (time zone shift)
Method 2: Time Module
import time
from datetime import datetime
total2 = int(time.mktime(datetimeobj.timetuple()))
print ("Method #2: Time Module")
print ("Before: %s" % datetimeobj)
print ("Seconds: %s " % total2)
print ("After: %s" % datetime.fromtimestamp(total2))
Output:
Method #2: Time Module
Before: 1970-10-01 12:00:00
Seconds: 23616000
After: 1970-10-01 12:00:00
Accuracy test: PASS
Method 3: Calendar Module
import calendar
from datetime import datetime
total3 = calendar.timegm(datetimeobj.timetuple())
print ("Method #3: Calendar Module")
print ("Before: %s" % datetimeobj)
print ("Seconds: %s " % total3)
print ("After: %s" % datetime.fromtimestamp(total3))
Output:
Method #3: Calendar Module
Before: 1970-10-01 12:00:00
Seconds: 23616000
After: 1970-10-01 16:00:00
Accuracy test: FAIL (time zone shift)
Method 4: Datetime Timestamp
from datetime import datetime
total4 = datetimeobj.timestamp()
print ("Method #4: datetime timestamp")
print ("Before: %s" % datetimeobj)
print ("Seconds: %s " % total4)
print ("After: %s" % datetime.fromtimestamp(total4))
Output:
Method #2: Time Module
Before: 1970-10-01 12:00:00
Seconds: 23616000
After: 1970-10-01 12:00:00
Accuracy test: PASS
Conclusion
All 4 methods convert datetime to epoch (total seconds)
Both the Manual method and Calendar module method are time zone aware.
Both datetime.timestamp() and time.mktime() methods are time zone unaware.
Simplest method: datetime.timestamp()
I do not see this in all of the answers, although I guess it is the default need:
t_start = datetime.now()
sleep(2)
t_end = datetime.now()
duration = t_end - t_start
print(round(duration.total_seconds()))
If you do not use .total_seconds(), it throws: TypeError: type datetime.timedelta doesn't define __round__ method.
Example:
>>> duration
datetime.timedelta(seconds=53, microseconds=621861)
>>> round(duration.total_seconds())
54
>>> duration.seconds
53
Taking duration.seconds takes only the seconds, leaving aside the microseconds, the same as if you ran math.floor(duration.total_seconds()).
To convert a datetime object that represents time in UTC to POSIX timestamp:
from datetime import timezone
seconds_since_epoch = utc_time.replace(tzinfo=timezone.utc).timestamp()
To convert a datetime object that represents time in the local timezone to POSIX timestamp:
import tzlocal # $ pip install tzlocal
local_timezone = tzlocal.get_localzone()
seconds_since_epoch = local_timezone.localize(local_time, is_dst=None).timestamp()
See How do I convert local time to UTC in Python? If the tz database is available on a given platform; a stdlib-only solution may work.
Follow the links if you need solutions for <3.3 Python versions.
I tried the standard library's calendar.timegm and it works quite well:
# convert a datetime to milliseconds since Epoch
def datetime_to_utc_milliseconds(aDateTime):
return int(calendar.timegm(aDateTime.timetuple())*1000)
Ref: https://docs.python.org/2/library/calendar.html#calendar.timegm
Python provides operation on datetime to compute the difference between two date. In your case that would be:
t - datetime.datetime(1970,1,1)
The value returned is a timedelta object from which you can use the member function total_seconds to get the value in seconds.
(t - datetime.datetime(1970,1,1)).total_seconds()
import datetime
import math
def getSeconds(inputDate):
time = datetime.date.today().strftime('%m/%d/%Y')
date_time = datetime.datetime.strptime(time, '%m/%d/%Y')
msg = inputDate
props = msg.split(".")
a_timedelta = datetime.timedelta
if(len(props)==3):
a_timedelta = date_time - datetime.datetime(int(props[0]),int(props[1]),int(props[2]))
else:
print("Invalid date format")
return
seconds = math.trunc(a_timedelta.total_seconds())
print(seconds)
return seconds
Example getSeconds("2022.1.1")
The standard way to find the processing time in ms of a block of code in python 3.x is the following:
import datetime
t_start = datetime.datetime.now()
# Here is the python3 code, you want
# to check the processing time of
t_end = datetime.datetime.now()
print("Time taken : ", (t_end - t_start).total_seconds()*1000, " ms")

How do I get the current time?

How do I get the current time?
Use datetime:
>>> import datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2009, 1, 6, 15, 8, 24, 78915)
>>> print(now)
2009-01-06 15:08:24.789150
For just the clock time without the date:
>>> now.time()
datetime.time(15, 8, 24, 78915)
>>> print(now.time())
15:08:24.789150
To save typing, you can import the datetime object from the datetime module:
>>> from datetime import datetime
Then remove the prefix datetime. from all of the above.
Use time.strftime():
>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2009-01-05 22:14:39'
from datetime import datetime
datetime.now().strftime('%Y-%m-%d %H:%M:%S')
Example output: '2013-09-18 11:16:32'
See list of strftime directives.
Similar to Harley's answer, but use the str() function for a quick-n-dirty, slightly more human readable format:
>>> from datetime import datetime
>>> str(datetime.now())
'2011-05-03 17:45:35.177000'
How do I get the current time in Python?
The time module
The time module provides functions that tell us the time in "seconds since the epoch" as well as other utilities.
import time
Unix Epoch Time
This is the format you should get timestamps in for saving in databases. It is a simple floating-point number that can be converted to an integer. It is also good for arithmetic in seconds, as it represents the number of seconds since Jan 1, 1970, 00:00:00, and it is memory light relative to the other representations of time we'll be looking at next:
>>> time.time()
1424233311.771502
This timestamp does not account for leap-seconds, so it's not linear - leap seconds are ignored. So while it is not equivalent to the international UTC standard, it is close, and therefore quite good for most cases of record-keeping.
This is not ideal for human scheduling, however. If you have a future event you wish to take place at a certain point in time, you'll want to store that time with a string that can be parsed into a datetime object or a serialized datetime object (these will be described later).
time.ctime
You can also represent the current time in the way preferred by your operating system (which means it can change when you change your system preferences, so don't rely on this to be standard across all systems, as I've seen others expect). This is typically user friendly, but doesn't typically result in strings one can sort chronologically:
>>> time.ctime()
'Tue Feb 17 23:21:56 2015'
You can hydrate timestamps into human readable form with ctime as well:
>>> time.ctime(1424233311.771502)
'Tue Feb 17 23:21:51 2015'
This conversion is also not good for record-keeping (except in text that will only be parsed by humans - and with improved Optical Character Recognition and Artificial Intelligence, I think the number of these cases will diminish).
datetime module
The datetime module is also quite useful here:
>>> import datetime
datetime.datetime.now
The datetime.now is a class method that returns the current time. It uses the time.localtime without the timezone info (if not given, otherwise see timezone aware below). It has a representation (which would allow you to recreate an equivalent object) echoed on the shell, but when printed (or coerced to a str), it is in human readable (and nearly ISO) format, and the lexicographic sort is equivalent to the chronological sort:
>>> datetime.datetime.now()
datetime.datetime(2015, 2, 17, 23, 43, 49, 94252)
>>> print(datetime.datetime.now())
2015-02-17 23:43:51.782461
datetime's utcnow
You can get a datetime object in UTC time, a global standard, by doing this:
>>> datetime.datetime.utcnow()
datetime.datetime(2015, 2, 18, 4, 53, 28, 394163)
>>> print(datetime.datetime.utcnow())
2015-02-18 04:53:31.783988
UTC is a time standard that is nearly equivalent to the GMT timezone. (While GMT and UTC do not change for Daylight Savings Time, their users may switch to other timezones, like British Summer Time, during the Summer.)
datetime timezone aware
However, none of the datetime objects we've created so far can be easily converted to various timezones. We can solve that problem with the pytz module:
>>> import pytz
>>> then = datetime.datetime.now(pytz.utc)
>>> then
datetime.datetime(2015, 2, 18, 4, 55, 58, 753949, tzinfo=<UTC>)
Equivalently, in Python 3 we have the timezone class with a utc timezone instance attached, which also makes the object timezone aware (but to convert to another timezone without the handy pytz module is left as an exercise to the reader):
>>> datetime.datetime.now(datetime.timezone.utc)
datetime.datetime(2015, 2, 18, 22, 31, 56, 564191, tzinfo=datetime.timezone.utc)
And we see we can easily convert to timezones from the original UTC object.
>>> print(then)
2015-02-18 04:55:58.753949+00:00
>>> print(then.astimezone(pytz.timezone('US/Eastern')))
2015-02-17 23:55:58.753949-05:00
You can also make a naive datetime object aware with the pytz timezone localize method, or by replacing the tzinfo attribute (with replace, this is done blindly), but these are more last resorts than best practices:
>>> pytz.utc.localize(datetime.datetime.utcnow())
datetime.datetime(2015, 2, 18, 6, 6, 29, 32285, tzinfo=<UTC>)
>>> datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
datetime.datetime(2015, 2, 18, 6, 9, 30, 728550, tzinfo=<UTC>)
The pytz module allows us to make our datetime objects timezone aware and convert the times to the hundreds of timezones available in the pytz module.
One could ostensibly serialize this object for UTC time and store that in a database, but it would require far more memory and be more prone to error than simply storing the Unix Epoch time, which I demonstrated first.
The other ways of viewing times are much more error-prone, especially when dealing with data that may come from different time zones. You want there to be no confusion as to which timezone a string or serialized datetime object was intended for.
If you're displaying the time with Python for the user, ctime works nicely, not in a table (it doesn't typically sort well), but perhaps in a clock. However, I personally recommend, when dealing with time in Python, either using Unix time, or a timezone aware UTC datetime object.
Do
from time import time
t = time()
t - float number, good for time interval measurement.
There is some difference for Unix and Windows platforms.
>>> from time import gmtime, strftime
>>> strftime("%a, %d %b %Y %X +0000", gmtime())
'Tue, 06 Jan 2009 04:54:56 +0000'
That outputs the current GMT in the specified format. There is also a localtime() method.
This page has more details.
The previous answers are all good suggestions, but I find it easiest to use ctime():
In [2]: from time import ctime
In [3]: ctime()
Out[3]: 'Thu Oct 31 11:40:53 2013'
This gives a nicely formatted string representation of the current local time.
The quickest way is:
>>> import time
>>> time.strftime("%Y%m%d")
'20130924'
If you need current time as a time object:
>>> import datetime
>>> now = datetime.datetime.now()
>>> datetime.time(now.hour, now.minute, now.second)
datetime.time(11, 23, 44)
You can use the time module:
>>> import time
>>> print(time.strftime("%d/%m/%Y"))
06/02/2015
The use of the capital Y gives the full year, and using y would give 06/02/15.
You could also use the following code to give a more lengthy time:
>>> time.strftime("%a, %d %b %Y %H:%M:%S")
'Fri, 06 Feb 2015 17:45:09'
.isoformat() is in the documentation, but not yet here
(this is mighty similar to #Ray Vega's answer):
>>> import datetime
>>> datetime.datetime.now().isoformat()
'2013-06-24T20:35:55.982000'
Why not ask the U.S. Naval Observatory, the official timekeeper of the United States Navy?
import requests
from lxml import html
page = requests.get('http://tycho.usno.navy.mil/cgi-bin/timer.pl')
tree = html.fromstring(page.content)
print(tree.xpath('//html//body//h3//pre/text()')[1])
If you live in the D.C. area (like me) the latency might not be too bad...
Using pandas to get the current time, kind of overkilling the problem at hand:
import pandas as pd
print(pd.datetime.now())
print(pd.datetime.now().date())
print(pd.datetime.now().year)
print(pd.datetime.now().month)
print(pd.datetime.now().day)
print(pd.datetime.now().hour)
print(pd.datetime.now().minute)
print(pd.datetime.now().second)
print(pd.datetime.now().microsecond)
Output:
2017-09-22 12:44:56.092642
2017-09-22
2017
9
22
12
44
56
92693
if you are using numpy already then directly you can use numpy.datetime64()
function.
import numpy as np
str(np.datetime64('now'))
for only date:
str(np.datetime64('today'))
or, if you are using pandas already then you can use pandas.to_datetime() function
import pandas as pd
str(pd.to_datetime('now'))
or,
str(pd.to_datetime('today'))
This is what I ended up going with:
>>>from time import strftime
>>>strftime("%m/%d/%Y %H:%M")
01/09/2015 13:11
Also, this table is a necessary reference for choosing the appropriate format codes to get the date formatted just the way you want it (from Python "datetime" documentation here).
datetime.now() returns the current time as a naive datetime object that represents time in the local timezone. That value may be ambiguous e.g., during DST transitions ("fall back"). To avoid ambiguity either UTC timezone should be used:
from datetime import datetime
utc_time = datetime.utcnow()
print(utc_time) # -> 2014-12-22 22:48:59.916417
Or a timezone-aware object that has the corresponding timezone info attached (Python 3.2+):
from datetime import datetime, timezone
now = datetime.now(timezone.utc).astimezone()
print(now) # -> 2014-12-23 01:49:25.837541+03:00
import datetime
date_time = datetime.datetime.now()
date = date_time.date() # Gives the date
time = date_time.time() # Gives the time
print date.year, date.month, date.day
print time.hour, time.minute, time.second, time.microsecond
Do dir(date) or any variables including the package. You can get all the attributes and methods associated with the variable.
>>> import datetime, time
>>> time = time.strftime("%H:%M:%S:%MS", time.localtime())
>>> print time
'00:21:38:20S'
This question doesn't need a new answer just for the sake of it ... a shiny new-ish toy/module, however, is enough justification. That being the Pendulum library, which appears to do the sort of things which arrow attempted, except without the inherent flaws and bugs which beset arrow.
For instance, the answer to the original question:
>>> import pendulum
>>> print(pendulum.now())
2018-08-14T05:29:28.315802+10:00
>>> print(pendulum.now('utc'))
2018-08-13T19:29:35.051023+00:00
There's a lot of standards which need addressing, including multiple RFCs and ISOs, to worry about. Ever get them mixed up; not to worry, take a little look into dir(pendulum.constants) There's a bit more than RFC and ISO formats there, though.
When we say local, though what do we mean? Well I mean:
>>> print(pendulum.now().timezone_name)
Australia/Melbourne
>>>
Presumably most of the rest of you mean somewhere else.
And on it goes. Long story short: Pendulum attempts to do for date and time what requests did for HTTP. It's worth consideration, particularly for both its ease of use and extensive documentation.
By default, now() function returns output in the YYYY-MM-DD HH:MM:SS:MS format. Use the below sample script to get the current date and time in a Python script and print results on the screen. Create file getDateTime1.py with the below content.
import datetime
currentDT = datetime.datetime.now()
print (str(currentDT))
The output looks like below:
2018-03-01 17:03:46.759624
Try the arrow module from http://crsmithdev.com/arrow/:
import arrow
arrow.now()
Or the UTC version:
arrow.utcnow()
To change its output, add .format():
arrow.utcnow().format('YYYY-MM-DD HH:mm:ss ZZ')
For a specific timezone:
arrow.now('US/Pacific')
An hour ago:
arrow.utcnow().replace(hours=-1)
Or if you want the gist.
arrow.get('2013-05-11T21:23:58.970460+00:00').humanize()
>>> '2 years ago'
Current time of a timezone
from datetime import datetime
import pytz
tz_NY = pytz.timezone('America/New_York')
datetime_NY = datetime.now(tz_NY)
print("NY time:", datetime_NY.strftime("%H:%M:%S"))
tz_London = pytz.timezone('Europe/London')
datetime_London = datetime.now(tz_London)
print("London time:", datetime_London.strftime("%H:%M:%S"))
tz_India = pytz.timezone('Asia/India')
datetime_India = datetime.now(tz_India)
print("India time:", datetime_India.strftime("%H:%M:%S"))
#list timezones
pytz.all_timezones
To get exactly 3 decimal points for milliseconds 11:34:23.751 run this:
def get_time_str(decimal_points=3):
return time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 10**decimal_points)
More context:
I want to get the time with milliseconds. A simple way to get them:
import time, datetime
print(datetime.datetime.now().time()) # 11:20:08.272239
# Or in a more complicated way
print(datetime.datetime.now().time().isoformat()) # 11:20:08.272239
print(datetime.datetime.now().time().strftime('%H:%M:%S.%f')) # 11:20:08.272239
# But do not use this:
print(time.strftime("%H:%M:%S.%f", time.localtime()), str) # 11:20:08.%f
But I want only milliseconds, right? The shortest way to get them:
import time
time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 1000)
# 11:34:23.751
Add or remove zeroes from the last multiplication to adjust number of decimal points, or just:
def get_time_str(decimal_points=3):
return time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 10**decimal_points)
If you just want the current timestamp in ms (for example, to measure execution time), you can also use the "timeit" module:
import timeit
start_time = timeit.default_timer()
do_stuff_you_want_to_measure()
end_time = timeit.default_timer()
print("Elapsed time: {}".format(end_time - start_time))
You can use this function to get the time (unfortunately it doesn't say AM or PM):
def gettime():
from datetime import datetime
return ((str(datetime.now())).split(' ')[1]).split('.')[0]
To get the hours, minutes, seconds and milliseconds to merge later, you can use these functions:
Hour:
def gethour():
from datetime import datetime
return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[0]
Minute:
def getminute():
from datetime import datetime
return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[1]
Second:
def getsecond():
from datetime import datetime
return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[2]
Millisecond:
def getmillisecond():
from datetime import datetime
return (str(datetime.now())).split('.')[1]
You can try the following
import datetime
now = datetime.datetime.now()
print(now)
or
import datetime
now = datetime.datetime.now()
print(now.strftime("%Y-%b-%d, %A %I:%M:%S"))
Because no one has mentioned it yet, and this is something I ran into recently... a pytz timezone's fromutc() method combined with datetime's utcnow() is the best way I've found to get a useful current time (and date) in any timezone.
from datetime import datetime
import pytz
JST = pytz.timezone("Asia/Tokyo")
local_time = JST.fromutc(datetime.utcnow())
If all you want is the time, you can then get that with local_time.time().
import datetime
todays_date = datetime.date.today()
print(todays_date)
>>> 2019-10-12
# adding strftime will remove the seconds
current_time = datetime.datetime.now().strftime('%H:%M')
print(current_time)
>>> 23:38
Method1: Getting Current Date and Time from system datetime
The datetime module supplies classes for manipulating dates and times.
Code
from datetime import datetime,date
print("Date: "+str(date.today().year)+"-"+str(date.today().month)+"-"+str(date.today().day))
print("Year: "+str(date.today().year))
print("Month: "+str(date.today().month))
print("Day: "+str(date.today().day)+"\n")
print("Time: "+str(datetime.today().hour)+":"+str(datetime.today().minute)+":"+str(datetime.today().second))
print("Hour: "+str(datetime.today().hour))
print("Minute: "+str(datetime.today().minute))
print("Second: "+str(datetime.today().second))
print("MilliSecond: "+str(datetime.today().microsecond))
Output will be like
Date: 2020-4-18
Year: 2020
Month: 4
Day: 18
Time: 19:30:5
Hour: 19
Minute: 30
Second: 5
MilliSecond: 836071
Method2: Getting Current Date and Time if Network is available
urllib package helps us to handle the url's that means webpages. Here we collects data from the webpage http://just-the-time.appspot.com/ and parses dateime from the webpage using the package dateparser.
Code
from urllib.request import urlopen
import dateparser
time_url = urlopen(u'http://just-the-time.appspot.com/')
datetime = time_url.read().decode("utf-8", errors="ignore").split(' ')[:-1]
date = datetime[0]
time = datetime[1]
print("Date: "+str(date))
print("Year: "+str(date.split('-')[0]))
print("Month: "+str(date.split('-')[1]))
print("Day: "+str(date.split('-')[2])+'\n')
print("Time: "+str(time))
print("Hour: "+str(time.split(':')[0]))
print("Minute: "+str(time.split(':')[1]))
print("Second: "+str(time.split(':')[2]))
Output will be like
Date: 2020-04-18
Year: 2020
Month: 04
Day: 18
Time: 14:17:10
Hour: 14
Minute: 17
Second: 10
Method3: Getting Current Date and Time from Local Time of the Machine
Python's time module provides a function for getting local time from the number of seconds elapsed since the epoch called localtime(). ctime() function takes seconds passed since epoch as an argument and returns a string representing local time.
Code
from time import time, ctime
datetime = ctime(time()).split(' ')
print("Date: "+str(datetime[4])+"-"+str(datetime[1])+"-"+str(datetime[2]))
print("Year: "+str(datetime[4]))
print("Month: "+str(datetime[1]))
print("Day: "+str(datetime[2]))
print("Week Day: "+str(datetime[0])+'\n')
print("Time: "+str(datetime[3]))
print("Hour: "+str(datetime[3]).split(':')[0])
print("Minute: "+str(datetime[3]).split(':')[1])
print("Second: "+str(datetime[3]).split(':')[2])
Output will be like
Date: 2020-Apr-18
Year: 2020
Month: Apr
Day: 18
Week Day: Sat
Time: 19:30:20
Hour: 19
Minute: 30
Second: 20

Categories

Resources