I have read all posts in Stackoverflow, documentation for "time" in python docs, but not found how to make float time.
import time
time.strftime('%H:%M:%S.%f', time.gmtime(60.5))
returns 00:01:00.%f
I want take 00:01:00.500
I wasn't able to find similar question.
Final solution is:
datetime.datetime.utcfromtimestamp(60.5).strftime('%H:%M:%S')+'.'+str(int(int(datetime.datetime.utcfromtimestamp(60.5).strftime('%f'))/1000))
The time module does not support the %f millisecond formatter because the time.struct_time tuple doesn't support milliseconds.
The datetime module does support milliseconds. Use that module instead:
import datetime
datetime.datetime.utcfromtimestamp(60.5).strftime('%H:%M:%S.%f')
Demo:
>>> datetime.datetime.utcfromtimestamp(60.5).strftime('%H:%M:%S.%f')
'00:01:00.500000'
Actually %f are microseconds:
from datetime import datetime
'{:%H:%M:%S.%f}'.format(datetime.utcfromtimestamp(60.5))
returns
00:01:00.500000
Related
I have a list of timestamps which look like so:
time_list=['2016-10-01T00:00:00+01:00','2016-10-01T23:00:00+00:00','2016-10-01T22:00:00+02:00',..]
I would like to apply a magic function to this list which gets them all in +00:00 timezone - this should result in (all timestamps should correctly adjusted to the +00:00 format):
ret_list=['2016-10-01T23:00:00+00:00','2016-10-01T23:00:00+00:00','2016-10-01T23:00:00+00:00',..]
You have to convert your isoformat strings to datetime objects first, change timezones to UTC and then stringify back.
If you are on python 3.7, according to this, you can use fromisoformat method of datetime, but if you don't, like me, I think the best option involves the use of dateutil module (you have to install it) and pytz:
import datetime as dt
from dateutil import parser
import pytz
time_list = ['2016-10-01T00:00:00+01:00','2016-10-01T23:00:00+00:00','2016-10-01T22:00:00+02:00']
utc_time_list = [parser.parse(x).astimezone(pytz.utc).isoformat() for x in time_list]
print(utc_time_list)
['2016-09-30T23:00:00+00:00', '2016-10-01T23:00:00+00:00', '2016-10-01T20:00:00+00:00']
I have a string date as 2015-03-25T00:00:00Z. How do I convert it to a unix epoch1426636800000.0
Are there any libraries in python to do that.
Using time, for example.
So first you need to convert the string to time object (or you can use datetime alternatively as halex mentioned) and then get the seconds since epoch.
>>> import time
>>> time.mktime(time.strptime('2015-03-25T00:00:00Z', '%Y-%m-%dT%H:%M:%SZ'))
1427241600.0
time.strptime(string[, format])
import time
print time.strptime("2015-03-25T00:00:00Z","%Y-%m-%dT%H:%M:%SZ")
If you have Python 3.3 or newer you can use the datetime module:
>>> import datetime
>>> datetime.datetime.strptime("2015-03-25T00:00:00Z", "%Y-%m-%dT%H:%M:%SZ").timestamp()
1427238000.0
You can use easy_date to make it easy:
import date_converter
timestamp = date_converter.string_to_timestamp("2015-03-25T00:00:00Z", "%Y-%m-%dT%H:%M:%SZ")
I have a time in UTC from which I want the number of seconds since epoch.
I am using strftime to convert it to the number of seconds. Taking 1st April 2012 as an example.
>>>datetime.datetime(2012,04,01,0,0).strftime('%s')
'1333234800'
1st of April 2012 UTC from epoch is 1333238400 but this above returns 1333234800 which is different by 1 hour.
So it looks like that strftime is taking my system time into account and applies a timezone shift somewhere. I thought datetime was purely naive?
How can I get around that? If possible avoiding to import other libraries unless standard. (I have portability concerns).
If you want to convert a python datetime to seconds since epoch you could do it explicitly:
>>> (datetime.datetime(2012,4,1,0,0) - datetime.datetime(1970,1,1)).total_seconds()
1333238400.0
In Python 3.3+ you can use timestamp() instead:
>>> datetime.datetime(2012,4,1,0,0).timestamp()
1333234800.0
Why you should not use datetime.strftime('%s')
Python doesn't actually support %s as an argument to strftime (if you check at http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior it's not in the list), the only reason it's working is because Python is passing the information to your system's strftime, which uses your local timezone.
>>> datetime.datetime(2012,04,01,0,0).strftime('%s')
'1333234800'
I had serious issues with Timezones and such. The way Python handles all that happen to be pretty confusing (to me). Things seem to be working fine using the calendar module (see links 1, 2, 3 and 4).
>>> import datetime
>>> import calendar
>>> aprilFirst=datetime.datetime(2012, 04, 01, 0, 0)
>>> calendar.timegm(aprilFirst.timetuple())
1333238400
import time
from datetime import datetime
now = datetime.now()
time.mktime(now.timetuple())
import time
from datetime import datetime
now = datetime.now()
# same as above except keeps microseconds
time.mktime(now.timetuple()) + now.microsecond * 1e-6
(Sorry, it wouldn't let me comment on existing answer)
if you just need a timestamp in unix /epoch time, this one line works:
created_timestamp = int((datetime.datetime.now() - datetime.datetime(1970,1,1)).total_seconds())
>>> created_timestamp
1522942073L
and depends only on datetime
works in python2 and python3
For an explicit timezone-independent solution, use the pytz library.
import datetime
import pytz
pytz.utc.localize(datetime.datetime(2012,4,1,0,0), is_dst=False).timestamp()
Output (float): 1333238400.0
This works in Python 2 and 3:
>>> import time
>>> import calendar
>>> calendar.timegm(time.gmtime())
1504917998
Just following the official docs...
https://docs.python.org/2/library/time.html#module-time
In Python 3.7
Return a datetime corresponding to a date_string in one of the formats
emitted by date.isoformat() and datetime.isoformat(). Specifically,
this function supports strings in the format(s)
YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]], where *
can match any single character.
https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat
I am trying to figure out the differences between the datetime and time modules, and what each should be used for.
I know that datetime provides both dates and time. What is the use of the time module?
Examples would be appreciated and differences concerning timezones would especially be of interest.
The time module is principally for working with Unix time stamps; expressed as a floating point number taken to be seconds since the Unix epoch. the datetime module can support many of the same operations, but provides a more object oriented set of types, and also has some limited support for time zones.
Stick to time to prevent DST ambiguity.
Use exclusively the system time module instead of the datetime module to prevent ambiguity issues with daylight savings time (DST).
Conversion to any time format, including local time, is pretty easy:
import time
t = time.time()
time.strftime('%Y-%m-%d %H:%M %Z', time.localtime(t))
'2019-05-27 12:03 CEST'
time.strftime('%Y-%m-%d %H:%M %Z', time.gmtime(t))
'2019-05-27 10:03 GMT'
time.time() is a floating point number representing the time in seconds since the system epoch. time.time() is ideal for unambiguous time stamping.
If the system additionally runs the network time protocol (NTP) dæmon, one ends up with a pretty solid time base.
Here is the documentation of the time module.
The time module can be used when you just need the time of a particular record - like lets say you have a seperate table/file for the transactions for each day, then you would just need the time.
However the time datatype is usually used to store the time difference between 2 points of time.
This can also be done using datetime, but if we are only dealing with time for a particular day, then time module can be used.
Datetime is used to store a particular data and time for a record. Like in a rental agency. The due date would be a datetime datatype.
Just noticed that time is more precise than datetime with an extra digit.
import time as tm
from datetime import datetime as dt
restime = tm.time()
resdtime = dt.timestamp(dt.now())
print("TIME:".rjust(10," "),restime)
print("DATETIME:".rjust(10," "),resdtime)
Output
TIME: 1637357103.7650678
DATETIME: 1637357103.765067
How to set default datetime format in python because i have multiple tuples to send via template on client side. This is not good approach to set each object's value to specified format. I want to set a datetime format on server side and these converted values will be shown to client. I tried
datetime.strftime("%Y-%m-%d %X")
but it is giving error.
strftime is a method of datetime objects - it doesn't set a default representation, which seems to be what you suggest. For example, you might call it like this:
>>> import datetime
>>> now = datetime.datetime.now()
>>> now.strftime("%Y-%m-%d %X")
'2011-03-17 10:14:12'
If you need to do this a lot, it would be worth creating a method that wraps this conversion of a datetime to a string. The documentation for the datetime module can be found here.
I'm not sure I understand your issue, but this might help
http://docs.djangoproject.com/en/dev/ref/settings/
there is a datetime format section, this sets datetime format globally.