w3resource

Python: Print structure time in local time


61. Local Time from Seconds

Write a Python program that takes a given number of seconds and passes since the epoch as an argument. Print structure time in local time.

Sample Solution:

Python Code:

# Import the time module
import time

# Convert the given timestamp (414538698) into a time structure and store it in the variable 'result'
result = time.localtime(414538698)

# Print a message indicating the result
print("\nResult:", result)

# Print a message indicating the year component of the time structure stored in 'result'
print("\nYear:", result.tm_year)

Output:

Result: time.struct_time(tm_year=1983, tm_mon=2, tm_mday=19, tm_hour=21, tm_min=38, tm_sec=18, tm_wday=5, tm_yday=50, tm_isdst=0)

Year: 1983

Explanation:

In the exercise above,

  • The code imports the "time" module, which provides functions for working with time.
  • It uses the "time.localtime()" function to convert the given timestamp (414538698) into a time structure representing the local time.
  • It stores the resulting time structure in the variable named 'result'.
  • It prints a message indicating the result, which is the time structure stored in 'result'.
  • It prints a message indicating the year component ('tm_year') of the time structure stored in 'result'.

Flowchart:

Flowchart: Print structure time in local time.

For more Practice: Solve these Related Problems:

  • Write a Python program that takes an integer number of seconds since the epoch and prints the corresponding local time as a structured time.
  • Write a Python script to convert a user-provided number of seconds into local time and then display the year component.
  • Write a Python function to accept seconds since the epoch, convert them to local time, and then output a formatted string of the result.
  • Write a Python program to use time.localtime on an input of seconds since the epoch and then print each component of the resulting structure.

Go to:


Previous: Write a Python program to print simple format of time, full names and the representation format and preferred date time format.
Next: Write a Python program that takes a tuple containing 9 elements corresponding to structure time as an argument and returns a string representing it.

Python Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.