Timestamp
Before moving into datetime class and objects, it is required to have a
knowledge on what are timestamps ? In Unix systems, it is the number
seconds between the given input and January 1 1970 at UTC. It is also known as
POSIX timestamp. In Python also the same thing happens when you convert a date
and time into timestamp.
Constructors in datetime
1. datetime.datetime ( year, month, day, hour, min, sec, microseconds, tzinfo)
Returns current date and time without timezone information.
2. datetime.today ( )
Returns current local time and date without time zone information. It takes no
parameter.
3. datetime.now (tz=None)
Returns current local time and date. By default the tzinfo is None, but it can
be passed as parameter, if the tzinfo abstract class has been implemented
separately by the user.
4. datetime.utcnow ()
Returns a naive datetime object which has current UTC date and time and tzinfo
is set to none. It takes no parameter.
5. datetime.fromtimestamp (timestamp, tz=None)
Takes the timestamp as input, tzinfo is an optional parameter. Returns the
local date and time which is represented by the input.
6. datetime.utcfromtimestamp (timestamp)
Returns the UTC date and time that corresponds to the input timestamp without
timezone information.
7. datetime.strptime (date_string, formatting string)
Returns the date time object that corresponds to the input date and time
string. The object will be formatted based on the formatting string given. If
the format string and the date string passed does not match, then value error
will arise.
Methods
Let us look at some of the important and frequently used methods of the
datetime class.
1. date(y,m,d)
Creates a date object with provided date, month and year.
2. time( h, min, sec, microsec)
Creates a time object with provided hour, minutes, seconds and micro seconds.
The tzinfo will be none by default.
3. timetz(h, min, sec, microsec, tzinfo)
Creates a time object with timezone information.
4. replace( year, month, day, hour, min, sec, microsec, tzinfo)
All the parameters are optional. You can specify which one among these has to
be replaced and the new value. After replacing it has to be assigned to the
datetime object to see the changes.
5. astimezone(tz)
Returns the local date and time to the specified tz(time zone). The tzinfo
class has to be implemented so that any of its methods do not return none.
Setting time zones
The time zone name can be set using a module named dateutil.
The time zones list will be available in this link and you can choose one
among that. Look at the example below.
Comments
Post a Comment