Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the time zone before calling strftime?

Tags:

c

unix

I represent dates using seconds (and microseconds) since 1970 as well as a time zone and dst flag. I want to print a representation of the date using strftime, but it uses the global value for timezone (extern long int timezone) that is picked up from the environment. How can I get strftime to print the zone of my choice?

like image 632
richcollins Avatar asked Oct 25 '09 06:10

richcollins


People also ask

How to set time zone in datetime Python?

Timezone aware object using datetime now(). time() function of datetime module. Then we will replace the value of the timezone in the tzinfo class of the object using the replace() function. After that convert the date value into ISO 8601 format using the isoformat() method.

What is Python timezone?

Python comes with a timestamp object named datetime. datetime . It can store date and time precise to the microsecond, and is qualified of timezone "aware" or "unaware", whether it embeds a timezone information or not. To build such an object based on the current time, one can use datetime.

How do I show time zone in Python?

You can get the current time in a particular timezone by using the datetime module with another module called pytz . You can then check for all available timezones with the snippet below: from datetime import datetime import pytz zones = pytz. all_timezones print(zones) # Output: all timezones of the world.


1 Answers

The following program sets the UNIX environment variable TZ with your required timezone and then prints a formatted time using strftime.

In the example below the timezone is set to U.S. Pacific Time Zone .

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main (int argc, char *argv[])
{
    struct tm *mt;
    time_t mtt;
    char ftime[10];

    setenv("TZ", "PST8PDT", 1);
    tzset();
    mtt = time(NULL);
    mt = localtime(&mtt);
    strftime(ftime,sizeof(ftime),"%Z %H%M",mt);

    printf("%s\n", ftime);
}
like image 109
David Avatar answered Oct 29 '22 10:10

David