datetime to ISO-8601 format [duplicate] - python

I have a file. In Python, I would like to take its creation time, and convert it to an ISO time (ISO 8601) string while preserving the fact that it was created in the Eastern Time Zone (ET).
How do I take the file's ctime and convert it to an ISO time string that indicates the Eastern Time Zone (and takes into account daylight savings time, if necessary)?

Local to ISO 8601:
import datetime
datetime.datetime.now().isoformat()
>>> 2020-03-20T14:28:23.382748
UTC to ISO 8601:
import datetime
datetime.datetime.utcnow().isoformat()
>>> 2020-03-20T01:30:08.180856
Local to ISO 8601 without microsecond:
import datetime
datetime.datetime.now().replace(microsecond=0).isoformat()
>>> 2020-03-20T14:30:43
UTC to ISO 8601 with TimeZone information (Python 3):
import datetime
datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()
>>> 2020-03-20T01:31:12.467113+00:00
UTC to ISO 8601 with Local TimeZone information without microsecond (Python 3):
import datetime
datetime.datetime.now().astimezone().replace(microsecond=0).isoformat()
>>> 2020-03-20T14:31:43+13:00
Local to ISO 8601 with TimeZone information (Python 3):
import datetime
datetime.datetime.now().astimezone().isoformat()
>>> 2020-03-20T14:32:16.458361+13:00
Notice there is a bug when using astimezone() on utc time. This gives an incorrect result:
datetime.datetime.utcnow().astimezone().isoformat() #Incorrect result
For Python 2, see and use pytz.

ISO 8601 allows a compact representation with no separators except for the T, so I like to use this one-liner to get a quick timestamp string:
>>> datetime.datetime.utcnow().strftime("%Y%m%dT%H%M%S.%fZ")
'20180905T140903.591680Z'
If you don't need the microseconds, just leave out the .%f part:
>>> datetime.datetime.utcnow().strftime("%Y%m%dT%H%M%SZ")
'20180905T140903Z'
For local time:
>>> datetime.datetime.now().strftime("%Y%m%dT%H%M%S")
'20180905T140903'
In general, I recommend you leave the punctuation in. RFC 3339 recommends that style because if everyone uses punctuation, there isn't a risk of things like multiple ISO 8601 strings being sorted in groups on their punctuation. So the one liner for a compliant string would be:
>>> datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")
'2018-09-05T14:09:03Z'

Here is what I use to convert to the XSD datetime format:
from datetime import datetime
datetime.now().replace(microsecond=0).isoformat()
# You get your ISO string
I came across this question when looking for the XSD date time format (xs:dateTime). I needed to remove the microseconds from isoformat.

ISO 8601 Time Representation
The international standard ISO 8601 describes a string representation for dates and times. Two simple examples of this format are
2010-12-16 17:22:15
20101216T172215
(which both stand for the 16th of December 2010), but the format also allows for sub-second resolution times and to specify time zones. This format is of course not Python-specific, but it is good for storing dates and times in a portable format. Details about this format can be found in the Markus Kuhn entry.
I recommend use of this format to store times in files.
One way to get the current time in this representation is to use strftime from the time module in the Python standard library:
>>> from time import strftime
>>> strftime("%Y-%m-%d %H:%M:%S")
'2010-03-03 21:16:45'
You can use the strptime constructor of the datetime class:
>>> from datetime import datetime
>>> datetime.strptime("2010-06-04 21:08:12", "%Y-%m-%d %H:%M:%S")
datetime.datetime(2010, 6, 4, 21, 8, 12)
The most robust is the Egenix mxDateTime module:
>>> from mx.DateTime.ISO import ParseDateTimeUTC
>>> from datetime import datetime
>>> x = ParseDateTimeUTC("2010-06-04 21:08:12")
>>> datetime.fromtimestamp(x)
datetime.datetime(2010, 3, 6, 21, 8, 12)
References
The Python time module documentation
The Python datetime class documentation
The Egenix mxDateTime class

I found the datetime.isoformat in the documentation. It seems to do what you want:
datetime.isoformat([sep])
Return a string representing the date and time in ISO 8601 format, YYYY-MM-DDTHH:MM:SS.mmmmmm or, if microsecond is 0, YYYY-MM-DDTHH:MM:SS
If utcoffset() does not return None, a 6-character string is appended, giving the UTC offset in (signed) hours and minutes: YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if microsecond is 0 YYYY-MM-DDTHH:MM:SS+HH:MM
The optional argument sep (default 'T') is a one-character separator, placed between the date and time portions of the result. For example,
>>>
>>> from datetime import tzinfo, timedelta, datetime
>>> class TZ(tzinfo):
... def utcoffset(self, dt): return timedelta(minutes=-399)
...
>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
'2002-12-25 00:00:00-06:39'

For those who are looking for a date-only solution, it is:
import datetime
datetime.date.today().isoformat()

The ISO 8601 time format does not store a time zone name, only the corresponding UTC offset is preserved.
To convert a file ctime to an ISO 8601 time string while preserving the UTC offset in Python 3:
>>> import os
>>> from datetime import datetime, timezone
>>> ts = os.path.getctime(some_file)
>>> dt = datetime.fromtimestamp(ts, timezone.utc)
>>> dt.astimezone().isoformat()
'2015-11-27T00:29:06.839600-05:00'
The code assumes that your local timezone is Eastern Time Zone (ET) and that your system provides a correct UTC offset for the given POSIX timestamp (ts), i.e., Python has access to a historical timezone database on your system or the time zone had the same rules at a given date.
If you need a portable solution; use the pytz module that provides access to the tz database:
>>> import os
>>> from datetime import datetime
>>> import pytz # pip install pytz
>>> ts = os.path.getctime(some_file)
>>> dt = datetime.fromtimestamp(ts, pytz.timezone('America/New_York'))
>>> dt.isoformat()
'2015-11-27T00:29:06.839600-05:00'
The result is the same in this case.
If you need the time zone name/abbreviation/zone id, store it separately.
>>> dt.astimezone().strftime('%Y-%m-%d %H:%M:%S%z (%Z)')
'2015-11-27 00:29:06-0500 (EST)'
Note: no, : in the UTC offset and EST timezone abbreviation is not part of the ISO 8601 time format. It is not unique.
Different libraries/different versions of the same library may use different time zone rules for the same date/timezone. If it is a future date then the rules might be unknown yet. In other words, the same UTC time may correspond to a different local time depending on what rules you use -- saving a time in ISO 8601 format preserves UTC time and the local time that corresponds to the current time zone rules in use on your platform. You might need to recalculate the local time on a different platform if it has different rules.

You'll need to use os.stat to get the file creation time and a combination of time.strftime and time.timezone for formatting:
>>> import time
>>> import os
>>> t = os.stat('C:/Path/To/File.txt').st_ctime
>>> t = time.localtime(t)
>>> formatted = time.strftime('%Y-%m-%d %H:%M:%S', t)
>>> tz = str.format('{0:+06.2f}', float(time.timezone) / 3600)
>>> final = formatted + tz
>>>
>>> final
'2008-11-24 14:46:08-02.00'

Just make the life simple please:
Use UTC time
Microsecond
one line code
f"{datetime.datetime.utcnow().isoformat()[:-3]}Z"
output:
2022-02-25T02:08:40.684Z

Standard RFC-3339 in milliseconds
I needed the time in this format for a LoRa application so I came up with this, I hope it helps:
from datetime import datetime
from time import strftime
# Get the current time in the format: 2021-03-20T16:51:23.644+01:00
def rfc3339_time_ms():
datetime_now = datetime.utcnow()
# Remove the microseconds
datetime_now_ms = datetime_now.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3]
# Add the timezone as "+/-HHMM", and the colon in "+/-HH:MM"
datetime_now_ms_tz = datetime_now_ms + strftime("%z")
rfc3339_ms_now = datetime_now_ms_tz[:-2] + ":" + datetime_now_ms_tz[-2:]
# print(f"Current time in ms in RFC-3339 format: {rfc3339_ms_now}")
return rfc3339_ms_now

Correct me if I'm wrong (I'm not), but the offset from UTC changes with daylight saving time. So you should use
tz = str.format('{0:+06.2f}', float(time.altzone) / 3600)
I also believe that the sign should be different:
tz = str.format('{0:+06.2f}', -float(time.altzone) / 3600)
I could be wrong, but I don't think so.

Adding a small variation to estani's excellent answer
Local to ISO 8601 with TimeZone and no microsecond info (Python 3):
import datetime, time
utc_offset_sec = time.altzone if time.localtime().tm_isdst else time.timezone
utc_offset = datetime.timedelta(seconds=-utc_offset_sec)
datetime.datetime.now().replace(microsecond=0, tzinfo=datetime.timezone(offset=utc_offset)).isoformat()
Sample Output:
'2019-11-06T12:12:06-08:00'
Tested that this output can be parsed by both Javascript Date and C# DateTime/DateTimeOffset

I agree with Jarek, and I furthermore note that the ISO offset separator character is a colon, so I think the final answer should be:
isodate.datetime_isoformat(datetime.datetime.now()) + str.format('{0:+06.2f}', -float(time.timezone) / 3600).replace('.', ':')

I've developed this function:
def iso_8601_format(dt):
"""YYYY-MM-DDThh:mm:ssTZD (1997-07-16T19:20:30-03:00)"""
if dt is None:
return ""
fmt_datetime = dt.strftime('%Y-%m-%dT%H:%M:%S')
tz = dt.utcoffset()
if tz is None:
fmt_timezone = "+00:00"
else:
fmt_timezone = str.format('{0:+06.2f}', float(tz.total_seconds() / 3600))
return fmt_datetime + fmt_timezone

import datetime, time
def convert_enddate_to_seconds(self, ts):
"""Takes ISO 8601 format(string) and converts into epoch time."""
dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')+\
datetime.timedelta(hours=int(ts[-5:-3]),
minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
seconds = time.mktime(dt.timetuple()) + dt.microsecond/1000000.0
return seconds
>>> import datetime, time
>>> ts = '2012-09-30T15:31:50.262-08:00'
>>> dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')+ datetime.timedelta(hours=int(ts[-5:-3]), minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
>>> seconds = time.mktime(dt.timetuple()) + dt.microsecond/1000000.0
>>> seconds
1348990310.26

Related

Format timedelta as time zone offset string

As input I have two timestamp strings, one is a local time, other is the same moment in UTC time. I want to get the difference between them (basically to get local time zone offset) as string in specific format, e.g. +1100 or -0500.
import datetime
local = '2018-01-31 18:34:42.172'
utc = '2018-01-31 23:34:42.172'
local_dt = datetime.datetime.strptime(local, '%Y-%m-%d %H:%M:%S.%f')
utc_dt = datetime.datetime.strptime(utc, '%Y-%m-%d %H:%M:%S.%f')
offset_timedelta = local_dt - utc_dt
offset = offset_timedelta.total_seconds() / 3600
offset
Out[8]: -5.0
Using timedelta I can get offset as float (-5.0 for example above). From there I probably may create a function to turn that float to string in format I want, but I am curious if there's any datetime/timedelta method or formatting which I am missing, or some string format which would do the job with cleaner code and more efficient.
Any help would be appreciated.
edit, since I see my question is not clear:
Is there a way to get "-0500" I need (string in that specific format, not a float), either by datetime library or string formatting?
You've actually done all the work already. But you can use the module dateutil to hide the messy details:
>>> local = '2018-01-31 18:34:42.172'
>>> utc = '2018-01-31 23:34:42.172'
>>> from dateutil import parser, relativedelta
>>> tzh=relativedelta.relativedelta(parser.parse(local), parser.parse(utc))
>>> tzh
relativedelta(hours=-5)
To format it the way you want:
>>> f"{tzh.hours:+03d}{abs(tzh.minutes):02d}"
'-0500'
Or, Python 2.6 to 3.5:
>>> "{hours:+03d}{minutes:02d}".format(hours=tzh.hours, minutes=abs(tzh.minutes))
'-0500'
The module dateutil isn't in the standard library but it is well worth the trouble of downloading. It can do far, far more than this.

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

Converting a unixtime to human readable date format [duplicate]

I have a string representing a unix timestamp (i.e. "1284101485") in Python, and I'd like to convert it to a readable date. When I use time.strftime, I get a TypeError:
>>>import time
>>>print time.strftime("%B %d %Y", "1284101485")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument must be 9-item sequence, not str
Use datetime module:
from datetime import datetime
ts = int('1284101485')
# if you encounter a "year is out of range" error the timestamp
# may be in milliseconds, try `ts /= 1000` in that case
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))
>>> from datetime import datetime
>>> datetime.fromtimestamp(1172969203.1)
datetime.datetime(2007, 3, 4, 0, 46, 43, 100000)
Taken from http://seehuhn.de/pages/pdate
The most voted answer suggests using fromtimestamp which is error prone since it uses the local timezone. To avoid issues a better approach is to use UTC:
datetime.datetime.utcfromtimestamp(posix_time).strftime('%Y-%m-%dT%H:%M:%SZ')
Where posix_time is the Posix epoch time you want to convert
>>> import time
>>> time.ctime(int("1284101485"))
'Fri Sep 10 16:51:25 2010'
>>> time.strftime("%D %H:%M", time.localtime(int("1284101485")))
'09/10/10 16:51'
There are two parts:
Convert the unix timestamp ("seconds since epoch") to the local time
Display the local time in the desired format.
A portable way to get the local time that works even if the local time zone had a different utc offset in the past and python has no access to the tz database is to use a pytz timezone:
#!/usr/bin/env python
from datetime import datetime
import tzlocal # $ pip install tzlocal
unix_timestamp = float("1284101485")
local_timezone = tzlocal.get_localzone() # get pytz timezone
local_time = datetime.fromtimestamp(unix_timestamp, local_timezone)
To display it, you could use any time format that is supported by your system e.g.:
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))
print(local_time.strftime("%B %d %Y")) # print date in your format
If you do not need a local time, to get a readable UTC time instead:
utc_time = datetime.utcfromtimestamp(unix_timestamp)
print(utc_time.strftime("%Y-%m-%d %H:%M:%S.%f+00:00 (UTC)"))
If you don't care about the timezone issues that might affect what date is returned or if python has access to the tz database on your system:
local_time = datetime.fromtimestamp(unix_timestamp)
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f"))
On Python 3, you could get a timezone-aware datetime using only stdlib (the UTC offset may be wrong if python has no access to the tz database on your system e.g., on Windows):
#!/usr/bin/env python3
from datetime import datetime, timezone
utc_time = datetime.fromtimestamp(unix_timestamp, timezone.utc)
local_time = utc_time.astimezone()
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))
Functions from the time module are thin wrappers around the corresponding C API and therefore they may be less portable than the corresponding datetime methods otherwise you could use them too:
#!/usr/bin/env python
import time
unix_timestamp = int("1284101485")
utc_time = time.gmtime(unix_timestamp)
local_time = time.localtime(unix_timestamp)
print(time.strftime("%Y-%m-%d %H:%M:%S", local_time))
print(time.strftime("%Y-%m-%d %H:%M:%S+00:00 (UTC)", utc_time))
In Python 3.6+:
import datetime
timestamp = 1642445213
value = datetime.datetime.fromtimestamp(timestamp)
print(f"{value:%Y-%m-%d %H:%M:%S}")
Output (local time)
2022-01-17 20:46:53
Explanation
Line #1: Import datetime library.
Line #2: Unix time which is seconds since 1970-01-01.
Line #3: Converts this to a unix time object, check with: type(value)
Line #4: Prints in the same format as strp. Local time. To print in UTC see example below.
Bonus
To save the date to a string then print it, use this:
my_date = f"{value:%Y-%m-%d %H:%M:%S}"
print(my_date)
To output in UTC:
value = datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc)
# 2022-01-17 18:50:52
Other than using time/datetime package, pandas can also be used to solve the same problem.Here is how we can use pandas to convert timestamp to readable date:
Timestamps can be in two formats:
13 digits(milliseconds) -
To convert milliseconds to date, use:
import pandas
result_ms=pandas.to_datetime('1493530261000',unit='ms')
str(result_ms)
Output: '2017-04-30 05:31:01'
10 digits(seconds) -
To convert seconds to date, use:
import pandas
result_s=pandas.to_datetime('1493530261',unit='s')
str(result_s)
Output: '2017-04-30 05:31:01'
For a human readable timestamp from a UNIX timestamp, I have used this in scripts before:
import os, datetime
datetime.datetime.fromtimestamp(float(os.path.getmtime("FILE"))).strftime("%B %d, %Y")
Output:
'December 26, 2012'
You can convert the current time like this
t=datetime.fromtimestamp(time.time())
t.strftime('%Y-%m-%d')
'2012-03-07'
To convert a date in string to different formats.
import datetime,time
def createDateObject(str_date,strFormat="%Y-%m-%d"):
timeStamp = time.mktime(time.strptime(str_date,strFormat))
return datetime.datetime.fromtimestamp(timeStamp)
def FormatDate(objectDate,strFormat="%Y-%m-%d"):
return objectDate.strftime(strFormat)
Usage
=====
o=createDateObject('2013-03-03')
print FormatDate(o,'%d-%m-%Y')
Output 03-03-2013
timestamp ="124542124"
value = datetime.datetime.fromtimestamp(timestamp)
exct_time = value.strftime('%d %B %Y %H:%M:%S')
Get the readable date from timestamp with time also, also you can change the format of the date.
Note that utcfromtimestamp can lead to unexpected results since it returns a naive datetime object. Python treats naive datetime as local time - while UNIX time refers to UTC.
This ambiguity can be avoided by setting the tz argument in fromtimestamp:
from datetime import datetime, timezone
dtobj = datetime.fromtimestamp(1284101485, timezone.utc)
>>> print(repr(dtobj))
datetime.datetime(2010, 9, 10, 6, 51, 25, tzinfo=datetime.timezone.utc)
Now you can format to string, e.g. an ISO8601 compliant format:
>>> print(dtobj.isoformat(timespec='milliseconds').replace('+00:00', 'Z'))
2010-09-10T06:51:25.000Z
Use the following codes, I hope it will solve your problem.
import datetime as dt
print(dt.datetime.fromtimestamp(int("1284101485")).strftime('%Y-%m-%d %H:%M:%S'))
Use datetime.strftime(format):
from datetime import datetime
unixtime = int('1284101485')
# Print with local time
print(datetime.fromtimestamp(unixtime).strftime('%Y-%m-%d %H:%M:%S'))
# Print with UTC time
print(datetime.utcfromtimestamp(unixtime).strftime('%Y-%m-%d %H:%M:%S'))
datetime.fromtimestamp(timestamp): Return the local date corresponding to the POSIX timestamp, such as is returned by time.time().
datetime.utcfromtimestamp(timestamp): Return the UTC datetime corresponding to the POSIX timestamp, with tzinfo None. (The resulting object is naive.)
import datetime
temp = datetime.datetime.fromtimestamp(1386181800).strftime('%Y-%m-%d %H:%M:%S')
print temp
Another way that this can be done using gmtime and format function;
from time import gmtime
print('{}-{}-{} {}:{}:{}'.format(*gmtime(1538654264.703337)))
Output: 2018-10-4 11:57:44
If you are working with a dataframe and do not want the series cannot be converted to class int error. Use the code below.
new_df= pd.to_datetime(df_new['time'], unit='s')
i just successfully used:
>>> type(tstamp)
pandas.tslib.Timestamp
>>> newDt = tstamp.date()
>>> type(newDt)
datetime.date
You can use easy_date to make it easy:
import date_converter
my_date_string = date_converter.timestamp_to_string(1284101485, "%B %d, %Y")
quick and dirty one liner:
'-'.join(str(x) for x in list(tuple(datetime.datetime.now().timetuple())[:6]))
'2013-5-5-1-9-43'

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

Converting datetime to POSIX time

How do I convert a datetime or date object into a POSIX timestamp in python? There are methods to create a datetime object out of a timestamp, but I don't seem to find any obvious ways to do the operation the opposite way.
import time, datetime
d = datetime.datetime.now()
print time.mktime(d.timetuple())
For UTC calculations, calendar.timegm is the inverse of time.gmtime.
import calendar, datetime
d = datetime.datetime.utcnow()
print calendar.timegm(d.timetuple())
Note that Python now (3.5.2) includes a built-in method for this in datetime objects:
>>> import datetime
>>> now = datetime.datetime(2020, 11, 18, 18, 52, 47, 874766)
>>> now.timestamp() # Local time
1605743567.874766
>>> now.replace(tzinfo=datetime.timezone.utc).timestamp() # UTC
1605725567.874766 # 5 hours delta (I'm in UTC-5)
In python, time.time() can return seconds as a floating point number that includes a decimal component with the microseconds. In order to convert a datetime back to this representation, you have to add the microseconds component because the direct timetuple doesn't include it.
import time, datetime
posix_now = time.time()
d = datetime.datetime.fromtimestamp(posix_now)
no_microseconds_time = time.mktime(d.timetuple())
has_microseconds_time = time.mktime(d.timetuple()) + d.microsecond * 0.000001
print posix_now
print no_microseconds_time
print has_microseconds_time
Best conversion from posix/epoch to datetime timestamp and the reverse:
this_time = datetime.datetime.utcnow() # datetime.datetime type
epoch_time = this_time.timestamp() # posix time or epoch time
this_time = datetime.datetime.fromtimestamp(epoch_time)
It depends
Is your datetime object timezone aware or naive?
Timezone Aware
If it is aware it's simple
from datetime import datetime, timezone
aware_date = datetime.now(tz=timezone.utc)
posix_timestamp = aware_date.timestamp()
as date.timestamp() gives you "POSIX timestamp"
NOTE: more accurate to call it an epoch/unix timestamp as it may not be POSIX compliant
Timezone Naive
If it's not timezone aware (naive), then you'd need to know what timezone it was originally in so we can use replace() to convert it into a timezone aware date object. Let's assume that you've stored/retrieved it as UTC Naive. Here we create one, as an example:
from datetime import datetime, timezone
naive_date = datetime.utcnow() # this date is naive, but is UTC based
aware_date = naive_date.replace(tzinfo=timezone.utc) # this date is no longer naive
# now we do as we did with the last one
posix_timestamp = aware_date.timestamp()
It's always better to get to a timezone aware date as soon as you can to prevent issues that can arise with naive dates (as Python will often assume they are local times and can mess you up)
NOTE: also be careful with your understanding of the epoch as it is platform dependent

Categories

Resources