Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: date, time formatting

I need to generate a local timestamp in a form of YYYYMMDDHHmmSSOHH'mm'. That OHH'mm' is one of +, -, Z and then there are hourhs and minutes followed by '.

Please, how do I get such a timestamp, denoting both local time zone and possible daylight saving?

like image 443
TarGz Avatar asked Mar 21 '10 12:03

TarGz


People also ask

What is the date time format in Python?

format is the format – 'yyyy-mm-dd'

How do I change date and time format in Python?

Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.

Is there a date format in Python?

A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.


2 Answers

import time  localtime   = time.localtime() timeString  = time.strftime("%Y%m%d%H%M%S", localtime)  # is DST in effect? timezone    = -(time.altzone if localtime.tm_isdst else time.timezone) timeString += "Z" if timezone == 0 else "+" if timezone > 0 else "-" timeString += time.strftime("%H'%M'", time.gmtime(abs(timezone))) 
like image 56
badp Avatar answered Oct 02 '22 04:10

badp


time.strftime will do for that,

And in linux, %z will just give you -HHMM format if environment variable is properly set.

>>> os.environ['TZ'] = 'EST' >>> time.strftime('%x %X %z') '03/21/10 08:16:33 -0500' 
like image 37
YOU Avatar answered Oct 02 '22 02:10

YOU